Date: (Mon) Jan 25, 2016
Data: Source: Training: https://www.kaggle.com/c/yelp-restaurant-photo-classification/download/train.csv.tgz
New: https://www.kaggle.com/c/yelp-restaurant-photo-classification/download/test.csv.tgz
Time period:
Based on analysis utilizing <> techniques,
Summary of key steps & error improvement stats:
Use plot.ly for interactive plots ?
varImp for randomForest crashes in caret version:6.0.41 -> submit bug report
extensions toward multiclass classification are scheduled for the next release
rm(list = ls())
set.seed(12345)
options(stringsAsFactors = FALSE)
source("~/Dropbox/datascience/R/myscript.R")
source("~/Dropbox/datascience/R/mydsutils.R")
## Loading required package: caret
## Loading required package: lattice
## Loading required package: ggplot2
source("~/Dropbox/datascience/R/myplot.R")
source("~/Dropbox/datascience/R/mypetrinet.R")
source("~/Dropbox/datascience/R/myplclust.R")
source("~/Dropbox/datascience/R/mytm.R")
# Gather all package requirements here
suppressPackageStartupMessages(require(doMC))
glbCores <- 6 # of cores on machine - 2
registerDoMC(glbCores)
suppressPackageStartupMessages(require(caret))
require(plyr)
## Loading required package: plyr
require(dplyr)
## Loading required package: dplyr
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:plyr':
##
## arrange, count, desc, failwith, id, mutate, rename, summarise,
## summarize
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
require(knitr)
## Loading required package: knitr
require(stringr)
## Loading required package: stringr
#source("dbgcaret.R")
#packageVersion("snow")
#require(sos); findFn("cosine", maxPages=2, sortby="MaxScore")
# Analysis control global variables
# Inputs
# url/name = "<pointer>"; if url specifies a zip file, name = "<filename>"
# sep = choose from c(NULL, "\t")
glbObsTrnFile <- list(url = "https://www.kaggle.com/c/yelp-restaurant-photo-classification/download/train.csv.tgz",
name = "train.csv")
glbObsNewFile <- list(url = "https://www.kaggle.com/c/yelp-restaurant-photo-classification/download/test.csv.tgz",
name = "test.csv") # default OR
#list(splitSpecs = list(method = NULL #select from c(NULL, "condition", "sample", "copy")
# ,nRatio = 0.3 # > 0 && < 1 if method == "sample"
# ,seed = 123 # any integer or glbObsTrnPartitionSeed if method == "sample"
# ,condition = # or 'is.na(<var>)'; '<var> <condition_operator> <value>'
# )
# )
glbInpMerge <- NULL #: default
# list(fnames = c("<fname1>", "<fname2>")) # files will be concatenated
glb_is_separate_newobs_dataset <- TRUE # or TRUE
glb_split_entity_newobs_datasets <- TRUE # FALSE not supported - use "copy" for glbObsNewFile$splitSpecs$method # select from c(FALSE, TRUE)
glbObsDropCondition <- NULL # : default
# enclose in single-quotes b/c condition might include double qoutes
# use | & ; NOT || &&
# '<condition>'
# 'grepl("^First Draft Video:", glbObsAll$Headline)'
# '(is.na(glbObsAll[, glb_rsp_var_raw]) & grepl("Train", glbObsAll[, glbFeatsId]))'
#nrow(do.call("subset",list(glbObsAll, parse(text=paste0("!(", glbObsDropCondition, ")")))))
glb_obs_repartition_train_condition <- NULL # : default
# "<condition>"
glb_max_fitobs <- NULL # or any integer
glbObsTrnPartitionSeed <- 123 # or any integer
glb_is_regression <- FALSE; glb_is_classification <- !glb_is_regression;
glb_is_binomial <- TRUE # or TRUE or FALSE
glb_rsp_var_raw <- "outdoor"
# for classification, the response variable has to be a factor
glb_rsp_var <- "outdoor.fctr"
# if the response factor is based on numbers/logicals e.g (0/1 OR TRUE/FALSE vs. "A"/"B"),
# or contains spaces (e.g. "Not in Labor Force")
# caret predict(..., type="prob") crashes
glb_map_rsp_raw_to_var <- #NULL
function(raw) {
# return(raw ^ 0.5)
# return(log(raw))
# return(log(1 + raw))
# return(log10(raw))
# return(exp(-raw / 2))
# ret_vals <- rep_len(NA, length(raw)); ret_vals[!is.na(raw)] <- ifelse(raw[!is.na(raw)] == 1, "Y", "N"); return(relevel(as.factor(ret_vals), ref="N"))
ret_vals <- rep_len(NA, length(raw)); ret_vals[!is.na(raw)] <- ifelse(raw[!is.na(raw)] != -1, "Y", "N"); return(relevel(as.factor(ret_vals), ref = "N"))
# as.factor(paste0("B", raw))
# as.factor(gsub(" ", "\\.", raw))
}
#if glb_rsp_var_raw is numeric:
#print(summary(glbObsAll[, glb_rsp_var_raw]))
#glb_map_rsp_raw_to_var(tst <- c(NA, as.numeric(summary(glbObsAll[, glb_rsp_var_raw]))))
#if glb_rsp_var_raw is character:
#print(table(glbObsAll[, glb_rsp_var_raw], useNA = "ifany"))
#print(table(glb_map_rsp_raw_to_var(tst <- glbObsAll[, glb_rsp_var_raw]), useNA = "ifany"))
glb_map_rsp_var_to_raw <- #NULL
function(var) {
# return(var ^ 2.0)
# return(exp(var))
# return(10 ^ var)
# return(-log(var) * 2)
# as.numeric(var)
levels(var)[as.numeric(var)]
# gsub("\\.", " ", levels(var)[as.numeric(var)])
# c("<=50K", " >50K")[as.numeric(var)]
# c(FALSE, TRUE)[as.numeric(var)]
}
#print(table(glb_map_rsp_var_to_raw(glb_map_rsp_raw_to_var(tst)), useNA = "ifany"))
if ((glb_rsp_var != glb_rsp_var_raw) && is.null(glb_map_rsp_raw_to_var))
stop("glb_map_rsp_raw_to_var function expected")
# List info gathered for various columns
# <col_name>: <description>; <notes>
# currently does not handle more than 1 column; consider concatenating multiple columns
# If glbFeatsId == NULL, ".rownames <- as.numeric(row.names())" is the default
glbFeatsId <- "business_id" # choose from c(NULL : default, "<id_feat>")
glbFeatsCategory <- NULL # choose from c(NULL : default, "<category_feat>")
# User-specified exclusions
glbFeatsExclude <- c(NULL
# Feats that shd be excluded due to known causation by prediction variable
# , "<feat1", "<feat2>"
# Feats that are linear combinations (alias in glm)
# Feature-engineering phase -> start by excluding all features except id & category & work each one in
,"labels","lunch","dinner","reserve","outdoor"
,"expensive","liquor","table","classy"
,"kids"
)
if (glb_rsp_var_raw != glb_rsp_var)
glbFeatsExclude <- union(glbFeatsExclude, glb_rsp_var_raw)
glbFeatsInteractionOnly <- list()
#glbFeatsInteractionOnly[["<child_feat>"]] <- "<parent_feat>"
glbFeatsDrop <- c(NULL
# , "<feat1>", "<feat2>"
)
glb_map_vars <- NULL # or c("<var1>", "<var2>")
glb_map_urls <- list();
# glb_map_urls[["<var1>"]] <- "<var1.url>"
glb_assign_pairs_lst <- NULL;
# glb_assign_pairs_lst[["<var1>"]] <- list(from=c(NA),
# to=c("NA.my"))
glb_assign_vars <- names(glb_assign_pairs_lst)
# Derived features; Use this mechanism to cleanse data ??? Cons: Data duplication ???
glbFeatsDerive <- list();
# glbFeatsDerive[["<feat.my.sfx>"]] <- list(
# mapfn = function(<arg1>, <arg2>) { return(function(<arg1>, <arg2>)) }
# , args = c("<arg1>", "<arg2>"))
#myprint_df(data.frame(ImageId = mapfn(glbObsAll$.src, glbObsAll$.pos)))
#data.frame(ImageId = mapfn(glbObsAll$.src, glbObsAll$.pos))[7045:7055, ]
# character
# mapfn = function(Week) { return(substr(Week, 1, 10)) }
# mapfn = function(descriptor) { return(plyr::revalue(descriptor, c(
# "ABANDONED BUILDING" = "OTHER",
# "**" = "**"
# ))) }
# mapfn = function(description) { mod_raw <- description;
# This is here because it does not work if it's in txt_map_filename
# mod_raw <- gsub(paste0(c("\n", "\211", "\235", "\317", "\333"), collapse = "|"), " ", mod_raw)
# Don't parse for "." because of ".com"; use customized gsub for that text
# mod_raw <- gsub("(\\w)(!|\\*|,|-|/)(\\w)", "\\1\\2 \\3", mod_raw);
# Some state acrnoyms need context for separation e.g.
# LA/L.A. could either be "Louisiana" or "LosAngeles"
# modRaw <- gsub("\\bL\\.A\\.( |,|')", "LosAngeles\\1", modRaw);
# OK/O.K. could either be "Oklahoma" or "Okay"
# modRaw <- gsub("\\bACA OK\\b", "ACA OKay", modRaw);
# modRaw <- gsub("\\bNow O\\.K\\.\\b", "Now OKay", modRaw);
# PR/P.R. could either be "PuertoRico" or "Public Relations"
# modRaw <- gsub("\\bP\\.R\\. Campaign", "PublicRelations Campaign", modRaw);
# VA/V.A. could either be "Virginia" or "VeteransAdministration"
# modRaw <- gsub("\\bthe V\\.A\\.\\:", "the VeteranAffairs:", modRaw);
#
# Custom mods
# return(mod_raw) }
# numeric
# Create feature based on record position/id in data
glbFeatsDerive[[".pos"]] <- list(
mapfn = function(.rnorm) { return(1:length(.rnorm)) }
, args = c(".rnorm"))
# glbFeatsDerive[[".pos.y"]] <- list(
# mapfn = function(.rnorm) { return(1:length(.rnorm)) }
# , args = c(".rnorm"))
# Add logs of numerics that are not distributed normally
# Derive & keep multiple transformations of the same feature, if normality is hard to achieve with just one transformation
# Right skew: logp1; sqrt; ^ 1/3; logp1(logp1); log10; exp(-<feat>/constant)
# glbFeatsDerive[["WordCount.log1p"]] <- list(
# mapfn = function(WordCount) { return(log1p(WordCount)) }
# , args = c("WordCount"))
# glbFeatsDerive[["WordCount.root2"]] <- list(
# mapfn = function(WordCount) { return(WordCount ^ (1/2)) }
# , args = c("WordCount"))
# glbFeatsDerive[["WordCount.nexp"]] <- list(
# mapfn = function(WordCount) { return(exp(-WordCount)) }
# , args = c("WordCount"))
#print(summary(glbObsAll$WordCount))
#print(summary(mapfn(glbObsAll$WordCount)))
# mapfn = function(HOSPI.COST) { return(cut(HOSPI.COST, 5, breaks = c(0, 100000, 200000, 300000, 900000), labels = NULL)) }
# mapfn = function(Rasmussen) { return(ifelse(sign(Rasmussen) >= 0, 1, 0)) }
# mapfn = function(startprice) { return(startprice ^ (1/2)) }
# mapfn = function(startprice) { return(log(startprice)) }
# mapfn = function(startprice) { return(exp(-startprice / 20)) }
# mapfn = function(startprice) { return(scale(log(startprice))) }
# mapfn = function(startprice) { return(sign(sprice.predict.diff) * (abs(sprice.predict.diff) ^ (1/10))) }
# factor
glbFeatsDerive[["lunch"]] <- list(
mapfn = function(labels) { return(factor(
sapply(labels, function(obsLabel) {if (is.na(obsLabel)) return(NA);
ifelse(any(as.numeric(unlist(str_split(obsLabel, " "))) %in% c(0)), "0", "-1") })
, levels = c("-1", "0"))) }
, args = c("labels"))
glbFeatsDerive[["dinner"]] <- list(
mapfn = function(labels) { return(factor(
sapply(labels, function(obsLabel) {if (is.na(obsLabel)) return(NA);
ifelse(any(as.numeric(unlist(str_split(obsLabel, " "))) %in% c(1)), "1", "-1") })
, levels = c("-1", "1"))) }
, args = c("labels"))
glbFeatsDerive[["reserve"]] <- list(
mapfn = function(labels) { return(factor(
sapply(labels, function(obsLabel) {if (is.na(obsLabel)) return(NA);
ifelse(any(as.numeric(unlist(str_split(obsLabel, " "))) %in% c(2)), "2", "-1") })
, levels = c("-1", "2"))) }
, args = c("labels"))
glbFeatsDerive[["outdoor"]] <- list(
mapfn = function(labels) { return(factor(
sapply(labels, function(obsLabel) {if (is.na(obsLabel)) return(NA);
ifelse(any(as.numeric(unlist(str_split(obsLabel, " "))) %in% c(3)), "3", "-1") })
, levels = c("-1", "3"))) }
, args = c("labels"))
glbFeatsDerive[["expensive"]] <- list(
mapfn = function(labels) { return(factor(
sapply(labels, function(obsLabel) {if (is.na(obsLabel)) return(NA);
ifelse(any(as.numeric(unlist(str_split(obsLabel, " "))) %in% c(4)), "4", "-1") })
, levels = c("-1", "4"))) }
, args = c("labels"))
glbFeatsDerive[["liquor"]] <- list(
mapfn = function(labels) { return(factor(
sapply(labels, function(obsLabel) {if (is.na(obsLabel)) return(NA);
ifelse(any(as.numeric(unlist(str_split(obsLabel, " "))) %in% c(5)), "5", "-1") })
, levels = c("-1", "5"))) }
, args = c("labels"))
glbFeatsDerive[["table"]] <- list(
mapfn = function(labels) { return(factor(
sapply(labels, function(obsLabel) {if (is.na(obsLabel)) return(NA);
ifelse(any(as.numeric(unlist(str_split(obsLabel, " "))) %in% c(6)), "6", "-1") })
, levels = c("-1", "6"))) }
, args = c("labels"))
glbFeatsDerive[["classy"]] <- list(
mapfn = function(labels) { return(factor(
sapply(labels, function(obsLabel) {if (is.na(obsLabel)) return(NA);
ifelse(any(as.numeric(unlist(str_split(obsLabel, " "))) %in% c(7)), "7", "-1") })
, levels = c("-1", "7"))) }
, args = c("labels"))
glbFeatsDerive[["kids"]] <- list(
mapfn = function(labels) { return(factor(
sapply(labels, function(obsLabel) {if (is.na(obsLabel)) return(NA);
ifelse(any(as.numeric(unlist(str_split(obsLabel, " "))) %in% c(8)), "8", "-1") })
, levels = c("-1", "8"))) }
, args = c("labels"))
# mapfn = function(PropR) { return(as.factor(ifelse(PropR >= 0.5, "Y", "N"))) }
# mapfn = function(productline, description) { as.factor(gsub(" ", "", productline)) }
# mapfn = function(purpose) { return(relevel(as.factor(purpose), ref="all_other")) }
# mapfn = function(raw) { tfr_raw <- as.character(cut(raw, 5));
# tfr_raw[is.na(tfr_raw)] <- "NA.my";
# return(as.factor(tfr_raw)) }
# mapfn = function(startprice.log10) { return(cut(startprice.log10, 3)) }
# mapfn = function(startprice.log10) { return(cut(sprice.predict.diff, c(-1000, -100, -10, -1, 0, 1, 10, 100, 1000))) }
# , args = c("<arg1>"))
# multiple args
# mapfn = function(id, date) { return(paste(as.character(id), as.character(date), sep = "#")) }
# mapfn = function(PTS, oppPTS) { return(PTS - oppPTS) }
# mapfn = function(startprice.log10.predict, startprice) {
# return(spdiff <- (10 ^ startprice.log10.predict) - startprice) }
# mapfn = function(productline, description) { as.factor(
# paste(gsub(" ", "", productline), as.numeric(nchar(description) > 0), sep = "*")) }
# mapfn = function(.src, .pos) {
# return(paste(.src, sprintf("%04d",
# ifelse(.src == "Train", .pos, .pos - 7049)
# ), sep = "#")) }
# # If glbObsAll is not sorted in the desired manner
# mapfn=function(Week) { return(coredata(lag(zoo(orderBy(~Week, glbObsAll)$ILI), -2, na.pad=TRUE))) }
# mapfn=function(ILI) { return(coredata(lag(zoo(ILI), -2, na.pad=TRUE))) }
# mapfn=function(ILI.2.lag) { return(log(ILI.2.lag)) }
# glbFeatsDerive[["<var1>"]] <- glbFeatsDerive[["<var2>"]]
glb_derive_vars <- names(glbFeatsDerive)
# tst <- "descr.my"; args_lst <- NULL; for (arg in glbFeatsDerive[[tst]]$args) args_lst[[arg]] <- glbObsAll[, arg]; print(head(args_lst[[arg]])); print(head(drv_vals <- do.call(glbFeatsDerive[[tst]]$mapfn, args_lst)));
# print(which_ix <- which(args_lst[[arg]] == 0.75)); print(drv_vals[which_ix]);
glbFeatsDateTime <- list()
# glbFeatsDateTime[["<DateTimeFeat>"]] <-
# c(format = "%Y-%m-%d %H:%M:%S", timezone = "America/New_York", impute.na = TRUE,
# last.ctg = TRUE, poly.ctg = TRUE)
glbFeatsPrice <- NULL # or c("<price_var>")
glbFeatsImage <- list() #list(<imageFeat> = list(patchSize = 10)) # if patchSize not specified, no patch computation
glbFeatsText <- list()
Sys.setlocale("LC_ALL", "C") # For english
## [1] "C/C/C/C/C/en_US.UTF-8"
#glbFeatsText[["<TextFeature>"]] <- list(NULL,
# ,names = myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL,
# <comma-separated-screened-names>
# ))))
# ,rareWords = myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL,
# <comma-separated-nonSCOWL-words>
# ))))
#)
# Text Processing Step: custom modifications not present in txt_munge -> use glbFeatsDerive
# Text Processing Step: universal modifications
glb_txt_munge_filenames_pfx <- "<projectId>_mytxt_"
# Text Processing Step: tolower
# Text Processing Step: myreplacePunctuation
# Text Processing Step: removeWords
glb_txt_stop_words <- list()
# Remember to use unstemmed words
if (length(glbFeatsText) > 0) {
require(tm)
require(stringr)
glb_txt_stop_words[["<txt_var>"]] <- sort(myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
# Remove any words from stopwords
# , setdiff(myreplacePunctuation(stopwords("english")), c("<keep_wrd1>", <keep_wrd2>"))
# Remove salutations
,"mr","mrs","dr","Rev"
# Remove misc
#,"th" # Happy [[:digit::]]+th birthday
# Remove terms present in Trn only or New only; search for "Partition post-stem"
# ,<comma-separated-terms>
# cor.y.train == NA
# ,unlist(strsplit(paste(c(NULL
# ,"<comma-separated-terms>"
# ), collapse=",")
# freq == 1; keep c("<comma-separated-terms-to-keep>")
# ,<comma-separated-terms>
# chisq.pval high (e.g. == 1); keep c("<comma-separated-terms-to-keep>")
# ,<comma-separated-terms>
# nzv.freqRatio high (e.g. >= glbFeatsNzvFreqMax); keep c("<comma-separated-terms-to-keep>")
# ,<comma-separated-terms>
)))))
}
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^man", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
#glbObsAll[glb_post_stem_words_terms_mtrx_lst[[txtFeat]][, 4866] > 0, c(glb_rsp_var, txtFeat)]
# To identify terms with a specific freq
#paste0(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], freq == 1)$term), collapse = ",")
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], freq <= 2)$term), collapse = ",")
#subset(glb_post_stem_words_terms_df_lst[[txtFeat]], term %in% c("zinger"))
# To identify terms with a specific freq &
# are not stemmed together later OR is value of color.fctr (e.g. gold)
#paste0(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], (freq == 1) & !(term %in% c("blacked","blemish","blocked","blocks","buying","cables","careful","carefully","changed","changing","chargers","cleanly","cleared","connect","connects","connected","contains","cosmetics","default","defaulting","defective","definitely","describe","described","devices","displays","drop","drops","engravement","excellant","excellently","feels","fix","flawlessly","frame","framing","gentle","gold","guarantee","guarantees","handled","handling","having","install","iphone","iphones","keeped","keeps","known","lights","line","lining","liquid","liquidation","looking","lots","manuals","manufacture","minis","most","mostly","network","networks","noted","opening","operated","performance","performs","person","personalized","photograph","physically","placed","places","powering","pre","previously","products","protection","purchasing","returned","rotate","rotation","running","sales","second","seconds","shipped","shuts","sides","skin","skinned","sticker","storing","thats","theres","touching","unusable","update","updates","upgrade","weeks","wrapped","verified","verify") ))$term), collapse = ",")
#print(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (freq <= 2)))
#glbObsAll[which(terms_mtrx[, 229] > 0), glbFeatsText]
# To identify terms with cor.y == NA
#orderBy(~-freq+term, subset(glb_post_stop_words_terms_df_lst[[txtFeat]], is.na(cor.y)))
#paste(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], is.na(cor.y))[, "term"]), collapse=",")
#orderBy(~-freq+term, subset(glb_post_stem_words_terms_df_lst[[txtFeat]], is.na(cor.y)))
# To identify terms with low cor.y.abs
#head(orderBy(~cor.y.abs+freq+term, subset(glb_post_stem_words_terms_df_lst[[txtFeat]], !is.na(cor.y))), 5)
# To identify terms with high chisq.pval
#subset(glb_post_stem_words_terms_df_lst[[txtFeat]], chisq.pval > 0.99)
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (chisq.pval > 0.99) & (freq <= 10))$term), collapse=",")
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (chisq.pval > 0.9))$term), collapse=",")
#head(orderBy(~-chisq.pval+freq+term, glb_post_stem_words_terms_df_lst[[txtFeat]]), 5)
#glbObsAll[glb_post_stem_words_terms_mtrx_lst[[txtFeat]][, 68] > 0, glbFeatsText]
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^m", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
# To identify terms with high nzv.freqRatio
#summary(glb_post_stem_words_terms_df_lst[[txtFeat]]$nzv.freqRatio)
#paste0(sort(setdiff(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (nzv.freqRatio >= glbFeatsNzvFreqMax) & (freq < 10) & (chisq.pval >= 0.05))$term, c( "128gb","3g","4g","gold","ipad1","ipad3","ipad4","ipadair2","ipadmini2","manufactur","spacegray","sprint","tmobil","verizon","wifion"))), collapse=",")
# To identify obs with a txt term
#tail(orderBy(~-freq+term, glb_post_stop_words_terms_df_lst[[txtFeat]]), 20)
#mydspObs(list(descr.my.contains="non"), cols=c("color", "carrier", "cellular", "storage"))
#grep("ever", dimnames(terms_stop_mtrx)$Terms)
#which(terms_stop_mtrx[, grep("ipad", dimnames(terms_stop_mtrx)$Terms)] > 0)
#glbObsAll[which(terms_stop_mtrx[, grep("16", dimnames(terms_stop_mtrx)$Terms)[1]] > 0), c(glbFeatsCategory, "storage", txtFeat)]
# Text Processing Step: screen for names # Move to glbFeatsText specs section in order of text processing steps
# glbFeatsText[["<txtFeat>"]]$names <- myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
# # Person names for names screening
# ,<comma-separated-list>
#
# # Company names
# ,<comma-separated-list>
#
# # Product names
# ,<comma-separated-list>
# ))))
# glbFeatsText[["<txtFeat>"]]$rareWords <- myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
# # Words not in SCOWL db
# ,<comma-separated-list>
# ))))
# To identify char vectors post glbFeatsTextMap
#grep("six(.*)hour", glb_txt_chr_lst[[txtFeat]], ignore.case = TRUE, value = TRUE)
#grep("[S|s]ix(.*)[H|h]our", glb_txt_chr_lst[[txtFeat]], value = TRUE)
# To identify whether terms shd be synonyms
#orderBy(~term, glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^moder", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ])
# term_row_df <- glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^came$", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ]
#
# cor(glb_post_stop_words_terms_mtrx_lst[[txtFeat]][glbObsAll$.lcn == "Fit", term_row_df$pos], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
# To identify which stopped words are "close" to a txt term
#sort(cluster_vars)
# Text Processing Step: stemDocument
# To identify stemmed txt terms
#glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^la$", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ]
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^con", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
#glbObsAll[which(terms_stem_mtrx[, grep("use", dimnames(terms_stem_mtrx)$Terms)[[1]]] > 0), c(glbFeatsId, "productline", txtFeat)]
#glbObsAll[which(TfIdf_stem_mtrx[, 191] > 0), c(glbFeatsId, glbFeatsCategory, txtFeat)]
#glbObsAll[which(glb_post_stop_words_terms_mtrx_lst[[txtFeat]][, 6165] > 0), c(glbFeatsId, glbFeatsCategory, txtFeat)]
#which(glbObsAll$UniqueID %in% c(11915, 11926, 12198))
# Text Processing Step: mycombineSynonyms
# To identify which terms are associated with not -> combine "could not" & "couldn't"
#findAssocs(glb_full_DTM_lst[[txtFeat]], "not", 0.05)
# To identify which synonyms should be combined
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^c", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
chk_comb_cor <- function(syn_lst) {
# cor(terms_stem_mtrx[glbObsAll$.src == "Train", grep("^(damag|dent|ding)$", dimnames(terms_stem_mtrx)[[2]])], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
print(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], term %in% syn_lst$syns))
print(subset(get_corpus_terms(tm_map(glbFeatsTextCorpus[[txtFeat]], mycombineSynonyms, list(syn_lst), lazy=FALSE)), term == syn_lst$word))
# cor(terms_stop_mtrx[glbObsAll$.src == "Train", grep("^(damage|dent|ding)$", dimnames(terms_stop_mtrx)[[2]])], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
# cor(rowSums(terms_stop_mtrx[glbObsAll$.src == "Train", grep("^(damage|dent|ding)$", dimnames(terms_stop_mtrx)[[2]])]), glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
}
#chk_comb_cor(syn_lst=list(word="cabl", syns=c("cabl", "cord")))
#chk_comb_cor(syn_lst=list(word="damag", syns=c("damag", "dent", "ding")))
#chk_comb_cor(syn_lst=list(word="dent", syns=c("dent", "ding")))
#chk_comb_cor(syn_lst=list(word="use", syns=c("use", "usag")))
glbFeatsTextSynonyms <- list()
# list parsed to collect glbFeatsText[[<txtFeat>]]$vldTerms
# glbFeatsTextSynonyms[["Hdln.my"]] <- list(NULL
# # people in places
# , list(word = "australia", syns = c("australia", "australian"))
# , list(word = "italy", syns = c("italy", "Italian"))
# , list(word = "newyork", syns = c("newyork", "newyorker"))
# , list(word = "Pakistan", syns = c("Pakistan", "Pakistani"))
# , list(word = "peru", syns = c("peru", "peruvian"))
# , list(word = "qatar", syns = c("qatar", "qatari"))
# , list(word = "scotland", syns = c("scotland", "scotish"))
# , list(word = "Shanghai", syns = c("Shanghai", "Shanzhai"))
# , list(word = "venezuela", syns = c("venezuela", "venezuelan"))
#
# # companies - needs to be data dependent
# # - e.g. ensure BNP in this experiment/feat always refers to BNPParibas
#
# # general synonyms
# , list(word = "Create", syns = c("Create","Creator"))
# , list(word = "cute", syns = c("cute","cutest"))
# , list(word = "Disappear", syns = c("Disappear","Fadeout"))
# , list(word = "teach", syns = c("teach", "taught"))
# , list(word = "theater", syns = c("theater", "theatre", "theatres"))
# , list(word = "understand", syns = c("understand", "understood"))
# , list(word = "weak", syns = c("weak", "weaken", "weaker", "weakest"))
# , list(word = "wealth", syns = c("wealth", "wealthi"))
#
# # custom synonyms (phrases)
#
# # custom synonyms (names)
# )
#glbFeatsTextSynonyms[["<txtFeat>"]] <- list(NULL
# , list(word="<stem1>", syns=c("<stem1>", "<stem1_2>"))
# )
for (txtFeat in names(glbFeatsTextSynonyms))
for (entryIx in 1:length(glbFeatsTextSynonyms[[txtFeat]])) {
glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$word <-
str_to_lower(glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$word)
glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$syns <-
str_to_lower(glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$syns)
}
glbFeatsTextSeed <- 181
# tm options include: check tm::weightSMART
glb_txt_terms_control <- list( # Gather model performance & run-time stats
# weighting = function(x) weightSMART(x, spec = "nnn")
# weighting = function(x) weightSMART(x, spec = "lnn")
# weighting = function(x) weightSMART(x, spec = "ann")
# weighting = function(x) weightSMART(x, spec = "bnn")
# weighting = function(x) weightSMART(x, spec = "Lnn")
#
weighting = function(x) weightSMART(x, spec = "ltn") # default
# weighting = function(x) weightSMART(x, spec = "lpn")
#
# weighting = function(x) weightSMART(x, spec = "ltc")
#
# weighting = weightBin
# weighting = weightTf
# weighting = weightTfIdf # : default
# termFreq selection criteria across obs: tm default: list(global=c(1, Inf))
, bounds = list(global = c(1, Inf))
# wordLengths selection criteria: tm default: c(3, Inf)
, wordLengths = c(1, Inf)
)
glb_txt_cor_var <- glb_rsp_var # : default # or c(<feat>)
# select one from c("union.top.val.cor", "top.cor", "top.val", default: "top.chisq", "sparse")
glbFeatsTextFilter <- "top.chisq"
glbFeatsTextTermsMax <- rep(10, length(glbFeatsText)) # :default
names(glbFeatsTextTermsMax) <- names(glbFeatsText)
# Text Processing Step: extractAssoc
glbFeatsTextAssocCor <- rep(1, length(glbFeatsText)) # :default
names(glbFeatsTextAssocCor) <- names(glbFeatsText)
# Remember to use stemmed terms
glb_important_terms <- list()
# Text Processing Step: extractPatterns (ngrams)
glbFeatsTextPatterns <- list()
#glbFeatsTextPatterns[[<txtFeat>>]] <- list()
#glbFeatsTextPatterns[[<txtFeat>>]] <- c(metropolitan.diary.colon = "Metropolitan Diary:")
# Have to set it even if it is not used
# Properties:
# numrows(glb_feats_df) << numrows(glbObsFit
# Select terms that appear in at least 0.2 * O(FP/FN(glbObsOOB)) ???
# numrows(glbObsOOB) = 1.1 * numrows(glbObsNew) ???
glb_sprs_thresholds <- NULL # or c(<txtFeat1> = 0.988, <txtFeat2> = 0.970, <txtFeat3> = 0.970)
glbFctrMaxUniqVals <- 20 # default: 20
glb_impute_na_data <- FALSE # or TRUE
glb_mice_complete.seed <- 144 # or any integer
glb_cluster <- FALSE # : default or TRUE
glb_cluster.seed <- 189 # or any integer
glb_cluster_entropy_var <- NULL # c(glb_rsp_var, as.factor(cut(glb_rsp_var, 3)), default: NULL)
glbFeatsTextClusterVarsExclude <- FALSE # default FALSE
glb_interaction_only_feats <- NULL # : default or c(<parent_feat> = "<child_feat>")
glbFeatsNzvFreqMax <- 19 # 19 : caret default
glbFeatsNzvUniqMin <- 10 # 10 : caret default
glbRFESizes <- list()
#glbRFESizes[["mdlFamily"]] <- c(4, 8, 16, 32, 64, 67, 68, 69) # Accuracy@69/70 = 0.8258
glbObsFitOutliers <- list()
# If outliers.n >= 10; consider concatenation of interaction vars
# glbObsFitOutliers[["<mdlFamily>"]] <- c(NULL
# is.na(.rstudent)
# max(.rstudent)
# is.na(.dffits)
# .hatvalues >= 0.99
# -38,167,642 < minmax(.rstudent) < 49,649,823
# , <comma-separated-<glbFeatsId>>
# )
glbObsTrnOutliers <- list()
glbObsTrnOutliers[["Final"]] <- union(glbObsFitOutliers[["All.X"]],
c(NULL
))
# influence.measures: car::outlier; rstudent; dffits; hatvalues; dfbeta; dfbetas
#mdlId <- "All.X##rcv#glm"; obs_df <- fitobs_df
#mdlId <- "RFE.X.glm"; obs_df <- fitobs_df
#mdlId <- "Final.glm"; obs_df <- trnobs_df
#mdlId <- "CSM2.X.glm"; obs_df <- fitobs_df
#print(outliers <- car::outlierTest(glb_models_lst[[mdlId]]$finalModel))
#mdlIdFamily <- paste0(head(unlist(str_split(mdlId, "\\.")), -1), collapse="."); obs_df <- dplyr::filter_(obs_df, interp(~(!(var %in% glbObsFitOutliers[[mdlIdFamily]])), var = as.name(glbFeatsId))); model_diags_df <- cbind(obs_df, data.frame(.rstudent=stats::rstudent(glb_models_lst[[mdlId]]$finalModel)), data.frame(.dffits=stats::dffits(glb_models_lst[[mdlId]]$finalModel)), data.frame(.hatvalues=stats::hatvalues(glb_models_lst[[mdlId]]$finalModel)));print(summary(model_diags_df[, c(".rstudent",".dffits",".hatvalues")])); table(cut(model_diags_df$.hatvalues, breaks=c(0.00, 0.98, 0.99, 1.00)))
#print(subset(model_diags_df, is.na(.rstudent))[, glbFeatsId])
#print(model_diags_df[which.max(model_diags_df$.rstudent), ])
#print(subset(model_diags_df, is.na(.dffits))[, glbFeatsId])
#print(model_diags_df[which.min(model_diags_df$.dffits), ])
#print(subset(model_diags_df, .hatvalues > 0.99)[, glbFeatsId])
#dffits_df <- merge(dffits_df, outliers_df, by="row.names", all.x=TRUE); row.names(dffits_df) <- dffits_df$Row.names; dffits_df <- subset(dffits_df, select=-Row.names)
#dffits_df <- merge(dffits_df, glbObsFit, by="row.names", all.x=TRUE); row.names(dffits_df) <- dffits_df$Row.names; dffits_df <- subset(dffits_df, select=-Row.names)
#subset(dffits_df, !is.na(.Bonf.p))
#mdlId <- "CSM.X.glm"; vars <- myextract_actual_feats(row.names(orderBy(reformulate(c("-", paste0(mdlId, ".imp"))), myget_feats_imp(glb_models_lst[[mdlId]]))));
#model_diags_df <- glb_get_predictions(model_diags_df, mdlId, glb_rsp_var)
#obs_ix <- row.names(model_diags_df) %in% names(outliers$rstudent)[1]
#obs_ix <- which(is.na(model_diags_df$.rstudent))
#obs_ix <- which(is.na(model_diags_df$.dffits))
#myplot_parcoord(obs_df=model_diags_df[, c(glbFeatsId, glbFeatsCategory, ".rstudent", ".dffits", ".hatvalues", glb_rsp_var, paste0(glb_rsp_var, mdlId), vars[1:min(20, length(vars))])], obs_ix=obs_ix, id_var=glbFeatsId, category_var=glbFeatsCategory)
#model_diags_df[row.names(model_diags_df) %in% names(outliers$rstudent)[c(1:2)], ]
#ctgry_diags_df <- model_diags_df[model_diags_df[, glbFeatsCategory] %in% c("Unknown#0"), ]
#myplot_parcoord(obs_df=ctgry_diags_df[, c(glbFeatsId, glbFeatsCategory, ".rstudent", ".dffits", ".hatvalues", glb_rsp_var, "startprice.log10.predict.RFE.X.glmnet", indep_vars[1:20])], obs_ix=row.names(ctgry_diags_df) %in% names(outliers$rstudent)[1], id_var=glbFeatsId, category_var=glbFeatsCategory)
#table(glbObsFit[model_diags_df[, glbFeatsCategory] %in% c("iPad1#1"), "startprice.log10.cut.fctr"])
#glbObsFit[model_diags_df[, glbFeatsCategory] %in% c("iPad1#1"), c(glbFeatsId, "startprice")]
# No outliers & .dffits == NaN
#myplot_parcoord(obs_df=model_diags_df[, c(glbFeatsId, glbFeatsCategory, glb_rsp_var, "startprice.log10.predict.RFE.X.glmnet", indep_vars[1:10])], obs_ix=seq(1:nrow(model_diags_df))[is.na(model_diags_df$.dffits)], id_var=glbFeatsId, category_var=glbFeatsCategory)
# Modify mdlId to (build & extract) "<FamilyId>#<Fit|Trn>#<caretMethod>#<preProc1.preProc2>#<samplingMethod>"
glb_models_lst <- list(); glb_models_df <- data.frame()
# Regression
if (glb_is_regression) {
glbMdlMethods <- c(NULL
# deterministic
#, "lm", # same as glm
, "glm", "bayesglm", "glmnet"
, "rpart"
# non-deterministic
, "gbm", "rf"
# Unknown
, "nnet" , "avNNet" # runs 25 models per cv sample for tunelength=5
, "svmLinear", "svmLinear2"
, "svmPoly" # runs 75 models per cv sample for tunelength=5
, "svmRadial"
, "earth"
, "bagEarth" # Takes a long time
)
} else
# Classification - Add ada (auto feature selection)
if (glb_is_binomial)
glbMdlMethods <- c(NULL
# deterministic
, "bagEarth" # Takes a long time
, "glm", "bayesglm", "glmnet"
, "nnet"
, "rpart"
# non-deterministic
, "gbm"
, "avNNet" # runs 25 models per cv sample for tunelength=5
, "rf"
# Unknown
, "lda", "lda2"
# svm models crash when predict is called -> internal to kernlab it should call predict without .outcome
, "svmLinear", "svmLinear2"
, "svmPoly" # runs 75 models per cv sample for tunelength=5
, "svmRadial"
, "earth"
) else
glbMdlMethods <- c(NULL
# deterministic
,"glmnet"
# non-deterministic
,"rf"
# Unknown
,"gbm","rpart"
)
glbMdlFamilies <- list(); glb_mdl_feats_lst <- list()
# family: Choose from c("RFE.X", "CSM.X", "All.X", "Best.Interact")
# methods: Choose from c(NULL, <method>, glbMdlMethods)
#glbMdlFamilies[["RFE.X"]] <- c("glmnet", "glm") # non-NULL vector is mandatory
glbMdlFamilies[["All.X"]] <- c("glmnet", "glm") # non-NULL vector is mandatory
#glbMdlFamilies[["Best.Interact"]] <- "glmnet" # non-NULL vector is mandatory
# Check if interaction features make RFE better
# glbMdlFamilies[["CSM.X"]] <- setdiff(glbMdlMethods, c("lda", "lda2")) # crashing due to category:.clusterid ??? #c("glmnet", "glm") # non-NULL list is mandatory
# glb_mdl_feats_lst[["CSM.X"]] <- c(NULL
# , <comma-separated-features-vector>
# )
# dAFeats.CSM.X %<d-% c(NULL
# # Interaction feats up to varImp(RFE.X.glmnet) >= 50
# , <comma-separated-features-vector>
# , setdiff(myextract_actual_feats(predictors(rfe_fit_results)), c(NULL
# , <comma-separated-features-vector>
# ))
# )
# glb_mdl_feats_lst[["CSM.X"]] <- "%<d-% dAFeats.CSM.X"
glbMdlFamilies[["Final"]] <- c(NULL) # NULL vector acceptable # c("glmnet", "glm")
glbMdlAllowParallel <- list()
#glbMdlAllowParallel[["<mdlId>"]] <- FALSE
# Check if tuning parameters make fit better; make it mdlFamily customizable ?
glbMdlTuneParams <- data.frame()
# When glmnet crashes at model$grid with error: ???
glmnetTuneParams <- rbind(data.frame()
,data.frame(parameter = "alpha", vals = "0.100 0.325 0.550 0.775 1.000")
,data.frame(parameter = "lambda", vals = "9.342e-02")
)
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams,
# cbind(data.frame(mdlId = "<mdlId>"),
# glmnetTuneParams))
#avNNet
# size=[1] 3 5 7 9; decay=[0] 1e-04 0.001 0.01 0.1; bag=[FALSE]; RMSE=1.3300906
#bagEarth
# degree=1 [2] 3; nprune=64 128 256 512 [1024]; RMSE=0.6486663 (up)
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
# ,data.frame(method = "bagEarth", parameter = "nprune", vals = "256")
# ,data.frame(method = "bagEarth", parameter = "degree", vals = "2")
# ))
#earth
# degree=[1]; nprune=2 [9] 17 25 33; RMSE=0.1334478
#gbm
# shrinkage=0.05 [0.10] 0.15 0.20 0.25; n.trees=100 150 200 [250] 300; interaction.depth=[1] 2 3 4 5; n.minobsinnode=[10]; RMSE=0.2008313
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
# ,data.frame(method = "gbm", parameter = "shrinkage", min = 0.05, max = 0.25, by = 0.05)
# ,data.frame(method = "gbm", parameter = "n.trees", min = 100, max = 300, by = 50)
# ,data.frame(method = "gbm", parameter = "interaction.depth", min = 1, max = 5, by = 1)
# ,data.frame(method = "gbm", parameter = "n.minobsinnode", min = 10, max = 10, by = 10)
# #seq(from=0.05, to=0.25, by=0.05)
# ))
#glmnet
# alpha=0.100 [0.325] 0.550 0.775 1.000; lambda=0.0005232693 0.0024288010 0.0112734954 [0.0523269304] 0.2428800957; RMSE=0.6164891
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
# ,data.frame(method = "glmnet", parameter = "alpha", vals = "0.550 0.775 0.8875 0.94375 1.000")
# ,data.frame(method = "glmnet", parameter = "lambda", vals = "9.858855e-05 0.0001971771 0.0009152152 0.0042480525 0.0197177130")
# ))
#nnet
# size=3 5 [7] 9 11; decay=0.0001 0.001 0.01 [0.1] 0.2; RMSE=0.9287422
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
# ,data.frame(method = "nnet", parameter = "size", vals = "3 5 7 9 11")
# ,data.frame(method = "nnet", parameter = "decay", vals = "0.0001 0.0010 0.0100 0.1000 0.2000")
# ))
#rf # Don't bother; results are not deterministic
# mtry=2 35 68 [101] 134; RMSE=0.1339974
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
# ,data.frame(method = "rf", parameter = "mtry", vals = "2 5 9 13 17")
# ))
#rpart
# cp=0.020 [0.025] 0.030 0.035 0.040; RMSE=0.1770237
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
# ,data.frame(method = "rpart", parameter = "cp", vals = "0.004347826 0.008695652 0.017391304 0.021739130 0.034782609")
# ))
#svmLinear
# C=0.01 0.05 [0.10] 0.50 1.00 2.00 3.00 4.00; RMSE=0.1271318; 0.1296718
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
# ,data.frame(method = "svmLinear", parameter = "C", vals = "0.01 0.05 0.1 0.5 1")
# ))
#svmLinear2
# cost=0.0625 0.1250 [0.25] 0.50 1.00; RMSE=0.1276354
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
# ,data.frame(method = "svmLinear2", parameter = "cost", vals = "0.0625 0.125 0.25 0.5 1")
# ))
#svmPoly
# degree=[1] 2 3 4 5; scale=0.01 0.05 [0.1] 0.5 1; C=0.50 1.00 [2.00] 3.00 4.00; RMSE=0.1276130
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
# ,data.frame(method="svmPoly", parameter="degree", min=1, max=5, by=1) #seq(1, 5, 1)
# ,data.frame(method="svmPoly", parameter="scale", vals="0.01, 0.05, 0.1, 0.5, 1")
# ,data.frame(method="svmPoly", parameter="C", vals="0.50, 1.00, 2.00, 3.00, 4.00")
# ))
#svmRadial
# sigma=[0.08674323]; C=0.25 0.50 1.00 [2.00] 4.00; RMSE=0.1614957
#glb2Sav(); all.equal(sav_models_df, glb_models_df)
glb_preproc_methods <- NULL
# c("YeoJohnson", "center.scale", "range", "pca", "ica", "spatialSign")
# Baseline prediction model feature(s)
glb_Baseline_mdl_var <- NULL # or c("<feat>")
glbMdlMetric_terms <- NULL # or matrix(c(
# 0,1,2,3,4,
# 2,0,1,2,3,
# 4,2,0,1,2,
# 6,4,2,0,1,
# 8,6,4,2,0
# ), byrow=TRUE, nrow=5)
glbMdlMetricSummary <- NULL # or "<metric_name>"
glbMdlMetricMaximize <- NULL # or FALSE (TRUE is not the default for both classification & regression)
glbMdlMetricSummaryFn <- NULL # or function(data, lev=NULL, model=NULL) {
# confusion_mtrx <- t(as.matrix(confusionMatrix(data$pred, data$obs)))
# #print(confusion_mtrx)
# #print(confusion_mtrx * glbMdlMetric_terms)
# metric <- sum(confusion_mtrx * glbMdlMetric_terms) / nrow(data)
# names(metric) <- glbMdlMetricSummary
# return(metric)
# }
glbMdlCheckRcv <- FALSE # Turn it on when needed; otherwise takes long time
glb_rcv_n_folds <- 3 # or NULL
glb_rcv_n_repeats <- 3 # or NULL
glb_clf_proba_threshold <- NULL # 0.5
# Model selection criteria
if (glb_is_regression)
glbMdlMetricsEval <- c("min.RMSE.OOB", "max.R.sq.OOB", "max.Adj.R.sq.fit", "min.RMSE.fit")
#glbMdlMetricsEval <- c("min.RMSE.fit", "max.R.sq.fit", "max.Adj.R.sq.fit")
if (glb_is_classification) {
if (glb_is_binomial)
glbMdlMetricsEval <-
c("max.Accuracy.OOB", "max.AUCROCR.OOB", "max.AUCpROC.OOB", "min.aic.fit", "max.Accuracy.fit") else
glbMdlMetricsEval <- c("max.Accuracy.OOB", "max.Kappa.OOB")
}
# select from NULL [no ensemble models], "auto" [all models better than MFO or Baseline], c(mdl_ids in glb_models_lst) [Typically top-rated models in auto]
glb_mdl_ensemble <- NULL
# "%<d-% setdiff(mygetEnsembleAutoMdlIds(), 'CSM.X.rf')"
# c(<comma-separated-mdlIds>
# )
# Only for classifications; for regressions remove "(.*)\\.prob" form the regex
# tmp_fitobs_df <- glbObsFit[, grep(paste0("^", gsub(".", "\\.", mygetPredictIds$value, fixed = TRUE), "CSM\\.X\\.(.*)\\.prob"), names(glbObsFit), value = TRUE)]; cor_mtrx <- cor(tmp_fitobs_df); cor_vctr <- sort(cor_mtrx[row.names(orderBy(~-Overall, varImp(glb_models_lst[["Ensemble.repeatedcv.glmnet"]])$imp))[1], ]); summary(cor_vctr); cor_vctr
#ntv.glm <- glm(reformulate(indep_vars, glb_rsp_var), family = "binomial", data = glbObsFit)
#step.glm <- step(ntv.glm)
glb_sel_mdl_id <- "All.X##rcv#glmnet" #select from c(NULL, "All.X##rcv#glmnet", "RFE.X##rcv#glmnet", <mdlId>)
glb_fin_mdl_id <- NULL #select from c(NULL, glb_sel_mdl_id)
glb_dsp_cols <- c(".pos", glbFeatsId, glbFeatsCategory, glb_rsp_var
# List critical cols excl. above
)
# Output specs
# lclgetfltout_df <- function(obsout_df) {
# require(tidyr)
# obsout_df <- obsout_df %>%
# tidyr::separate("ImageId.x.y", c(".src", ".pos", "x", "y"),
# sep = "#", remove = TRUE, extra = "merge")
#
# # dplyr::summarize(xMeanN = mean(as.numeric(x)), yMeanN = mean(as.numeric(y)))
#
# return(fmnout_df)
# }
glbObsOut <- list(NULL
# glbFeatsId will be the first output column, by default
,vars = list()
# ,mapFn = function(obsout_df) {
# }
)
#obsout_df <- savobsout_df
glbObsOut$mapFn <- function(obsout_df) {
set.seed(997)
txfout_df <- obsout_df %>%
dplyr::mutate(
lunch = levels(glbObsTrn[, "lunch" ])[
round(mean(as.numeric(glbObsTrn[, "lunch" ])), 0)],
dinner = levels(glbObsTrn[, "dinner" ])[
round(mean(as.numeric(glbObsTrn[, "dinner" ])), 0)],
reserve = levels(glbObsTrn[, "reserve" ])[
round(mean(as.numeric(glbObsTrn[, "reserve" ])), 0)],
# outdoor = levels(glbObsTrn[, "outdoor" ])[
# rbinom(nrow(obsout_df), 1, mean(as.numeric(glbObsTrn[, "outdoor" ])) - 1) + 1],
outdoor =
ifelse(levels(glbObsTrn[, "outdoor.fctr" ])[as.numeric(outdoor.fctr)] == "N", "-1", "3"),
expensive = levels(glbObsTrn[, "expensive"])[
round(mean(as.numeric(glbObsTrn[, "expensive"])), 0)],
liquor = levels(glbObsTrn[, "liquor" ])[
round(mean(as.numeric(glbObsTrn[, "liquor" ])), 0)],
table = levels(glbObsTrn[, "table" ])[
round(mean(as.numeric(glbObsTrn[, "table" ])), 0)],
classy = levels(glbObsTrn[, "classy" ])[
round(mean(as.numeric(glbObsTrn[, "classy" ])), 0)],
kids = levels(glbObsTrn[, "kids" ])[
round(mean(as.numeric(glbObsTrn[, "kids" ])), 0)]
)
print("ObsNew output class tables:")
print(sapply(c("lunch","dinner","reserve","outdoor",
"expensive","liquor","table",
"classy","kids"),
function(feat) table(txfout_df[, feat], useNA = "ifany")))
txfout_df <- txfout_df %>%
dplyr::mutate(labels = "") %>%
dplyr::mutate(labels =
ifelse(lunch != "-1", paste(labels, lunch ), labels)) %>%
dplyr::mutate(labels =
ifelse(dinner != "-1", paste(labels, dinner ), labels)) %>%
dplyr::mutate(labels =
ifelse(reserve != "-1", paste(labels, reserve ), labels)) %>%
dplyr::mutate(labels =
ifelse(outdoor != "-1", paste(labels, outdoor ), labels)) %>%
dplyr::mutate(labels =
ifelse(expensive != "-1", paste(labels, expensive), labels)) %>%
dplyr::mutate(labels =
ifelse(liquor != "-1", paste(labels, liquor ), labels)) %>%
dplyr::mutate(labels =
ifelse(table != "-1", paste(labels, table ), labels)) %>%
dplyr::mutate(labels =
ifelse(classy != "-1", paste(labels, classy ), labels)) %>%
dplyr::mutate(labels =
ifelse(kids != "-1", paste(labels, kids ), labels)) %>%
dplyr::select(business_id, labels)
return(txfout_df)
}
#if (!is.null(glbObsOut$mapFn)) obsout_df <- glbObsOut$mapFn(obsout_df); print(head(obsout_df))
glb_out_obs <- NULL # select from c(NULL : default to "new", "all", "new", "trn")
if (glb_is_classification && glb_is_binomial) {
# glbObsOut$vars[["Proba.Y"]] <-
# "%<d-% glbObsNew[, mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$prob]"
glbObsOut$vars[[glb_rsp_var]] <-
"%<d-% glbObsNew[, mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$value]"
} else {
# glbObsOut$vars[[glbFeatsId]] <-
# "%<d-% as.integer(gsub('Test#', '', glbObsNew[, glbFeatsId]))"
glbObsOut$vars[[glb_rsp_var]] <-
"%<d-% glbObsNew[, mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$value]"
# for (outVar in setdiff(glbFeatsExcludeLcl, glb_rsp_var_raw))
# glbObsOut$vars[[outVar]] <-
# paste0("%<d-% mean(glbObsAll[, \"", outVar, "\"], na.rm = TRUE)")
}
# glbObsOut$vars[[glb_rsp_var_raw]] <- glb_rsp_var_raw
# glbObsOut$vars[[paste0(head(unlist(strsplit(mygetPredictIds$value, "")), -1), collapse = "")]] <-
glbOutStackFnames <- NULL #: default
# c("ebayipads_txt_assoc1_out_bid1_stack.csv") # manual stack
# c("ebayipads_finmdl_bid1_out_nnet_1.csv") # universal stack
glbOut <- list(pfx = "YelpRest_rndm_")
# lclImageSampleSeed <- 129
glbOutDataVizFname <- NULL # choose from c(NULL, "<projectId>_obsall.csv")
glbChunks <- list(labels = c("set_global_options_wd","set_global_options"
,"import.data","inspect.data","scrub.data","transform.data"
,"extract.features"
,"extract.features.datetime","extract.features.image","extract.features.price"
,"extract.features.text","extract.features.string"
,"extract.features.end"
,"manage.missing.data","cluster.data","partition.data.training","select.features"
,"fit.models_0","fit.models_1","fit.models_2","fit.models_3"
,"fit.data.training_0","fit.data.training_1"
,"predict.data.new"
,"display.session.info"))
# To ensure that all chunks in this script are in glbChunks
if (!is.null(chkChunksLabels <- knitr::all_labels()) && # knitr::all_labels() doesn't work in console runs
!identical(chkChunksLabels, glbChunks$labels)) {
print(sprintf("setdiff(chkChunksLabels, glbChunks$labels): %s",
setdiff(chkChunksLabels, glbChunks$labels)))
print(sprintf("setdiff(glbChunks$labels, chkChunksLabels): %s",
setdiff(glbChunks$labels, chkChunksLabels)))
}
glbChunks[["first"]] <- NULL #default: script will load envir from previous chunk
glbChunks[["last"]] <- NULL #"extract.features.end" #NULL #default: script will save envir at end of this chunk
#mysavChunk(glbOut$pfx, glbChunks[["last"]])
# Inspect max OOB FP
#chkObsOOB <- subset(glbObsOOB, !label.fctr.All.X..rcv.glmnet.is.acc)
#chkObsOOBFP <- subset(chkObsOOB, label.fctr.All.X..rcv.glmnet == "left_eye_center") %>% dplyr::mutate(Probability1 = label.fctr.All.X..rcv.glmnet.prob) %>% select(-.src, -.pos, -x, -y) %>% lclgetfltout_df() %>% mutate(obj.distance = (((as.numeric(x) - left_eye_center_x.int) ^ 2) + ((as.numeric(y) - left_eye_center_y.int) ^ 2)) ^ 0.5) %>% dplyr::top_n(5, obj.distance) %>% dplyr::top_n(5, -patch.cor)
#
#newImgObs <- glbObsNew[(glbObsNew$ImageId == "Test#0001"), ]; print(newImgObs[which.max(newImgObs$label.fctr.Final..rcv.glmnet.prob), ])
#OOBImgObs <- glbObsOOB[(glbObsOOB$ImageId == "Train#0003"), ]; print(OOBImgObs[which.max(OOBImgObs$label.fctr.All.X..rcv.glmnet.prob), ])
#load("<scriptName>_extract.features.end.RData", verbose = TRUE)
#mygetImage(which(glbObsAll[, glbFeatsId] == "Train#0003"), names(glbFeatsImage)[1], plot = TRUE, featHighlight = c("left_eye_center_x", "left_eye_center_y"), ovrlHighlight = c(66, 35))
# Depict process
glb_analytics_pn <- petrinet(name = "glb_analytics_pn",
trans_df = data.frame(id = 1:6,
name = c("data.training.all","data.new",
"model.selected","model.final",
"data.training.all.prediction","data.new.prediction"),
x=c( -5,-5,-15,-25,-25,-35),
y=c( -5, 5, 0, 0, -5, 5)
),
places_df=data.frame(id=1:4,
name=c("bgn","fit.data.training.all","predict.data.new","end"),
x=c( -0, -20, -30, -40),
y=c( 0, 0, 0, 0),
M0=c( 3, 0, 0, 0)
),
arcs_df = data.frame(
begin = c("bgn","bgn","bgn",
"data.training.all","model.selected","fit.data.training.all",
"fit.data.training.all","model.final",
"data.new","predict.data.new",
"data.training.all.prediction","data.new.prediction"),
end = c("data.training.all","data.new","model.selected",
"fit.data.training.all","fit.data.training.all","model.final",
"data.training.all.prediction","predict.data.new",
"predict.data.new","data.new.prediction",
"end","end")
))
#print(ggplot.petrinet(glb_analytics_pn))
print(ggplot.petrinet(glb_analytics_pn) + coord_flip())
## Loading required package: grid
glb_analytics_avl_objs <- NULL
glb_chunks_df <- myadd_chunk(NULL, "import.data")
## label step_major step_minor label_minor bgn end elapsed
## 1 import.data 1 0 0 14.874 NA NA
1.0: import data## [1] "Reading file ./data/train.csv..."
## [1] "dimensions of data in ./data/train.csv: 2,000 rows x 2 cols"
## business_id labels
## 1 1000 1 2 3 4 5 6 7
## 2 1001 0 1 6 8
## 3 100 1 2 4 5 6 7
## 4 1006 1 2 4 5 6
## 5 1010 0 6 8
## 6 101 1 2 3 4 5 6
## business_id labels
## 69 1102 6 8
## 305 1479 0 3 8
## 1019 2829 0 2 3 8
## 1455 3650 8
## 1468 3675 1 2 3 4 5 6 7
## 1978 959 3 5 6 8
## business_id labels
## 1995 99 1 2 4 5 6 7
## 1996 991 1 2 3 5 6 7
## 1997 993 3 6 8
## 1998 997 8
## 1999 998 1 2 4 5 6 7
## 2000 999 1 2 5 6 7
## 'data.frame': 2000 obs. of 2 variables:
## $ business_id: int 1000 1001 100 1006 1010 101 1011 1012 1014 1015 ...
## $ labels : chr "1 2 3 4 5 6 7" "0 1 6 8" "1 2 4 5 6 7" "1 2 4 5 6" ...
## - attr(*, "comment")= chr "glbObsTrn"
## NULL
## [1] "Reading file ./data/test.csv..."
## [1] "dimensions of data in ./data/test.csv: 10,000 rows x 1 cols"
## business_id
## 1 003sg
## 2 00er5
## 3 00kad
## 4 00mc6
## 5 00q7x
## 6 00v0t
## business_id
## 12 01mrb
## 1789 6ey8p
## 3881 dqqme
## 3912 dv9lg
## 4024 ebyno
## 4625 gkb3z
## business_id
## 9995 zyrif
## 9996 zyvg6
## 9997 zyvjj
## 9998 zz8g4
## 9999 zzxkg
## 10000 zzxwm
## 'data.frame': 10000 obs. of 1 variable:
## $ business_id: chr "003sg" "00er5" "00kad" "00mc6" ...
## - attr(*, "comment")= chr "glbObsNew"
## NULL
## [1] "Creating new feature: .pos..."
## [1] "Creating new feature: lunch..."
## [1] "Creating new feature: dinner..."
## [1] "Creating new feature: reserve..."
## [1] "Creating new feature: outdoor..."
## [1] "Creating new feature: expensive..."
## [1] "Creating new feature: liquor..."
## [1] "Creating new feature: table..."
## [1] "Creating new feature: classy..."
## [1] "Creating new feature: kids..."
## [1] "Partition stats:"
## Loading required package: sqldf
## Loading required package: gsubfn
## Loading required package: proto
## Loading required package: RSQLite
## Loading required package: DBI
## Loading required package: tcltk
## outdoor .src .n
## 1 <NA> Test 10000
## 2 3 Train 1003
## 3 -1 Train 997
## outdoor .src .n
## 1 <NA> Test 10000
## 2 3 Train 1003
## 3 -1 Train 997
## Loading required package: RColorBrewer
## .src .n
## 1 Test 10000
## 2 Train 2000
## Loading required package: lazyeval
## Loading required package: gdata
## gdata: read.xls support for 'XLS' (Excel 97-2004) files ENABLED.
##
## gdata: read.xls support for 'XLSX' (Excel 2007+) files ENABLED.
##
## Attaching package: 'gdata'
## The following objects are masked from 'package:dplyr':
##
## combine, first, last
## The following object is masked from 'package:stats':
##
## nobs
## The following object is masked from 'package:utils':
##
## object.size
## [1] "Found 0 duplicates by all features:"
## NULL
## label step_major step_minor label_minor bgn end elapsed
## 1 import.data 1 0 0 14.874 35.275 20.402
## 2 inspect.data 2 0 0 35.276 NA NA
2.0: inspect data## Loading required package: reshape2
## outdoor.-1 outdoor.3 outdoor.NA
## Test NA NA 10000
## Train 997 1003 NA
## outdoor.-1 outdoor.3 outdoor.NA
## Test NA NA 1
## Train 0.4985 0.5015 NA
## [1] "numeric data missing in glbObsAll: "
## lunch dinner reserve outdoor expensive liquor table
## 10000 10000 10000 10000 10000 10000 10000
## classy kids
## 10000 10000
## [1] "numeric data w/ 0s in glbObsAll: "
## lunch
## 671
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## business_id labels
## 0 NA
## outdoor outdoor.fctr .n
## 1 <NA> <NA> 10000
## 2 3 Y 1003
## 3 -1 N 997
## Warning: Removed 1 rows containing missing values (position_stack).
## outdoor.fctr.N outdoor.fctr.Y outdoor.fctr.NA
## Test NA NA 10000
## Train 997 1003 NA
## outdoor.fctr.N outdoor.fctr.Y outdoor.fctr.NA
## Test NA NA 1
## Train 0.4985 0.5015 NA
## label step_major step_minor label_minor bgn end elapsed
## 2 inspect.data 2 0 0 35.276 39.491 4.215
## 3 scrub.data 2 1 1 39.491 NA NA
2.1: scrub data## [1] "numeric data missing in glbObsAll: "
## lunch dinner reserve outdoor expensive
## 10000 10000 10000 10000 10000
## liquor table classy kids outdoor.fctr
## 10000 10000 10000 10000 10000
## [1] "numeric data w/ 0s in glbObsAll: "
## lunch
## 671
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## business_id labels
## 0 NA
## label step_major step_minor label_minor bgn end elapsed
## 3 scrub.data 2 1 1 39.491 40.969 1.479
## 4 transform.data 2 2 2 40.970 NA NA
2.2: transform data## label step_major step_minor label_minor bgn end elapsed
## 4 transform.data 2 2 2 40.970 41.144 0.174
## 5 extract.features 3 0 0 41.144 NA NA
3.0: extract features## label step_major step_minor label_minor bgn
## 5 extract.features 3 0 0 41.144
## 6 extract.features.datetime 3 1 1 41.166
## end elapsed
## 5 41.165 0.021
## 6 NA NA
3.1: extract features datetime## label step_major step_minor label_minor bgn
## 1 extract.features.datetime.bgn 1 0 0 41.193
## end elapsed
## 1 NA NA
## label step_major step_minor label_minor bgn
## 6 extract.features.datetime 3 1 1 41.166
## 7 extract.features.image 3 2 2 41.204
## end elapsed
## 6 41.204 0.038
## 7 NA NA
3.2: extract features image## label step_major step_minor label_minor bgn end
## 1 extract.features.image.bgn 1 0 0 41.245 NA
## elapsed
## 1 NA
## label step_major step_minor label_minor bgn
## 1 extract.features.image.bgn 1 0 0 41.245
## 2 extract.features.image.end 2 0 0 41.255
## end elapsed
## 1 41.255 0.01
## 2 NA NA
## label step_major step_minor label_minor bgn
## 1 extract.features.image.bgn 1 0 0 41.245
## 2 extract.features.image.end 2 0 0 41.255
## end elapsed
## 1 41.255 0.01
## 2 NA NA
## label step_major step_minor label_minor bgn end
## 7 extract.features.image 3 2 2 41.204 41.266
## 8 extract.features.price 3 3 3 41.266 NA
## elapsed
## 7 0.062
## 8 NA
3.3: extract features price## label step_major step_minor label_minor bgn end
## 1 extract.features.price.bgn 1 0 0 41.3 NA
## elapsed
## 1 NA
## label step_major step_minor label_minor bgn end
## 8 extract.features.price 3 3 3 41.266 41.31
## 9 extract.features.text 3 4 4 41.311 NA
## elapsed
## 8 0.044
## 9 NA
3.4: extract features text## label step_major step_minor label_minor bgn end
## 1 extract.features.text.bgn 1 0 0 41.357 NA
## elapsed
## 1 NA
## label step_major step_minor label_minor bgn end
## 9 extract.features.text 3 4 4 41.311 41.367
## 10 extract.features.string 3 5 5 41.368 NA
## elapsed
## 9 0.056
## 10 NA
3.5: extract features string## label step_major step_minor label_minor bgn end
## 1 extract.features.string.bgn 1 0 0 41.401 NA
## elapsed
## 1 NA
## label step_major step_minor
## 1 extract.features.string.bgn 1 0
## 2 extract.features.stringfactorize.str.vars 2 0
## label_minor bgn end elapsed
## 1 0 41.401 41.411 0.01
## 2 0 41.411 NA NA
## business_id labels .src
## "business_id" "labels" ".src"
## label step_major step_minor label_minor bgn end
## 10 extract.features.string 3 5 5 41.368 41.425
## 11 extract.features.end 3 6 6 41.425 NA
## elapsed
## 10 0.057
## 11 NA
3.6: extract features end## [1] "Summary for lunch:"
##
## -1 0 <NA>
## Test 0 0 10000
## Train 1329 671 0
## [1] "Summary for dinner:"
##
## -1 1 <NA>
## Test 0 0 10000
## Train 1007 993 0
## [1] "Summary for reserve:"
##
## -1 2 <NA>
## Test 0 0 10000
## Train 974 1026 0
## [1] "Summary for outdoor:"
##
## -1 3 <NA>
## Test 0 0 10000
## Train 997 1003 0
## [1] "Summary for expensive:"
##
## -1 4 <NA>
## Test 0 0 10000
## Train 1453 547 0
## [1] "Summary for liquor:"
##
## -1 5 <NA>
## Test 0 0 10000
## Train 751 1249 0
## [1] "Summary for table:"
##
## -1 6 <NA>
## Test 0 0 10000
## Train 640 1360 0
## [1] "Summary for classy:"
##
## -1 7 <NA>
## Test 0 0 10000
## Train 1428 572 0
## [1] "Summary for kids:"
##
## -1 8 <NA>
## Test 0 0 10000
## Train 762 1238 0
## time trans "bgn " "fit.data.training.all " "predict.data.new " "end "
## 0.0000 multiple enabled transitions: data.training.all data.new model.selected firing: data.training.all
## 1.0000 1 2 1 0 0
## 1.0000 multiple enabled transitions: data.training.all data.new model.selected model.final data.training.all.prediction firing: data.new
## 2.0000 2 1 1 1 0
## label step_major step_minor label_minor bgn end
## 11 extract.features.end 3 6 6 41.425 42.401
## 12 manage.missing.data 4 0 0 42.402 NA
## elapsed
## 11 0.976
## 12 NA
4.0: manage missing data## [1] "numeric data missing in glbObsAll: "
## lunch dinner reserve outdoor expensive
## 10000 10000 10000 10000 10000
## liquor table classy kids outdoor.fctr
## 10000 10000 10000 10000 10000
## [1] "numeric data w/ 0s in glbObsAll: "
## lunch
## 671
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## business_id labels
## 0 NA
## [1] "numeric data missing in glbObsAll: "
## lunch dinner reserve outdoor expensive
## 10000 10000 10000 10000 10000
## liquor table classy kids outdoor.fctr
## 10000 10000 10000 10000 10000
## [1] "numeric data w/ 0s in glbObsAll: "
## lunch
## 671
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## business_id labels
## 0 NA
## label step_major step_minor label_minor bgn end
## 12 manage.missing.data 4 0 0 42.402 42.742
## 13 cluster.data 5 0 0 42.743 NA
## elapsed
## 12 0.341
## 13 NA
5.0: cluster data## label step_major step_minor label_minor bgn end
## 13 cluster.data 5 0 0 42.743 42.802
## 14 partition.data.training 6 0 0 42.802 NA
## elapsed
## 13 0.059
## 14 NA
6.0: partition data training## [1] "partition.data.training chunk: setup: elapsed: 0.00 secs"
## [1] "partition.data.training chunk: strata_mtrx complete: elapsed: 0.15 secs"
## [1] "partition.data.training chunk: obs_freq_df complete: elapsed: 0.15 secs"
## Loading required package: sampling
##
## Attaching package: 'sampling'
## The following objects are masked from 'package:survival':
##
## cluster, strata
## The following object is masked from 'package:caret':
##
## cluster
## [1] "partition.data.training chunk: Fit/OOB partition complete: elapsed: 0.63 secs"
## outdoor.-1 outdoor.3 outdoor.NA
## NA NA 10000
## Fit 499 502 NA
## OOB 498 501 NA
## outdoor.-1 outdoor.3 outdoor.NA
## NA NA 1
## Fit 0.4985015 0.5014985 NA
## OOB 0.4984985 0.5015015 NA
## .category .n.Fit .n.OOB .n.Tst .freqRatio.Fit .freqRatio.OOB
## 1 .dummy 1001 999 10000 1 1
## .freqRatio.Tst
## 1 1
## [1] "glbObsAll: "
## [1] 12000 17
## [1] "glbObsTrn: "
## [1] 2000 17
## [1] "glbObsFit: "
## [1] 1001 16
## [1] "glbObsOOB: "
## [1] 999 16
## [1] "glbObsNew: "
## [1] 10000 16
## [1] "partition.data.training chunk: teardown: elapsed: 0.86 secs"
## label step_major step_minor label_minor bgn end
## 14 partition.data.training 6 0 0 42.802 43.728
## 15 select.features 7 0 0 43.729 NA
## elapsed
## 14 0.926
## 15 NA
7.0: select features## Warning in cor(data.matrix(entity_df[, sel_feats]), y =
## as.numeric(entity_df[, : the standard deviation is zero
## cor.y exclude.as.feat cor.y.abs cor.high.X freqRatio
## outdoor 1.00000000 1 1.00000000 NA 1.006018
## liquor 0.10041620 1 0.10041620 NA 1.663116
## reserve 0.03893534 1 0.03893534 NA 1.053388
## .pos 0.02749730 0 0.02749730 NA 1.000000
## expensive 0.01722814 1 0.01722814 NA 2.656307
## classy 0.01580482 1 0.01580482 NA 2.496503
## lunch -0.00530855 1 0.00530855 NA 1.980626
## .rnorm -0.00804272 0 0.00804272 NA 1.000000
## dinner -0.03998016 1 0.03998016 NA 1.014099
## table -0.05582304 1 0.05582304 NA 2.125000
## kids -0.07589517 1 0.07589517 NA 1.624672
## .category NA 1 NA NA 0.000000
## percentUnique zeroVar nzv is.cor.y.abs.low
## outdoor 1e-01 FALSE FALSE FALSE
## liquor 1e-01 FALSE FALSE FALSE
## reserve 1e-01 FALSE FALSE FALSE
## .pos 1e+02 FALSE FALSE FALSE
## expensive 1e-01 FALSE FALSE FALSE
## classy 1e-01 FALSE FALSE FALSE
## lunch 1e-01 FALSE FALSE TRUE
## .rnorm 1e+02 FALSE FALSE FALSE
## dinner 1e-01 FALSE FALSE FALSE
## table 1e-01 FALSE FALSE FALSE
## kids 1e-01 FALSE FALSE FALSE
## .category 5e-02 TRUE TRUE NA
## Warning in myplot_scatter(plt_feats_df, "percentUnique", "freqRatio",
## colorcol_name = "nzv", : converting nzv to class:factor
## Warning: Removed 2 rows containing missing values (geom_point).
## Warning: Removed 2 rows containing missing values (geom_point).
## Warning: Removed 2 rows containing missing values (geom_point).
## cor.y exclude.as.feat cor.y.abs cor.high.X freqRatio
## .category NA 1 NA NA 0
## percentUnique zeroVar nzv is.cor.y.abs.low
## .category 0.05 TRUE TRUE NA
## [1] "numeric data missing in glbObsAll: "
## lunch dinner reserve outdoor expensive
## 10000 10000 10000 10000 10000
## liquor table classy kids outdoor.fctr
## 10000 10000 10000 10000 10000
## [1] "numeric data w/ 0s in glbObsAll: "
## lunch
## 671
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## business_id labels .lcn
## 0 NA 10000
## [1] "glb_feats_df:"
## [1] 12 12
## id exclude.as.feat rsp_var
## outdoor.fctr outdoor.fctr TRUE TRUE
## id cor.y exclude.as.feat cor.y.abs cor.high.X
## outdoor outdoor 1 TRUE 1 NA
## outdoor.fctr outdoor.fctr NA TRUE NA NA
## freqRatio percentUnique zeroVar nzv is.cor.y.abs.low
## outdoor 1.006018 0.1 FALSE FALSE FALSE
## outdoor.fctr NA NA NA NA NA
## interaction.feat shapiro.test.p.value rsp_var_raw id_var
## outdoor NA NA TRUE NA
## outdoor.fctr NA NA NA NA
## rsp_var
## outdoor NA
## outdoor.fctr TRUE
## [1] "glb_feats_df vs. glbObsAll: "
## character(0)
## [1] "glbObsAll vs. glb_feats_df: "
## character(0)
## label step_major step_minor label_minor bgn end elapsed
## 15 select.features 7 0 0 43.729 45.381 1.653
## 16 fit.models 8 0 0 45.382 NA NA
8.0: fit modelsfit.models_0_chunk_df <- myadd_chunk(NULL, "fit.models_0_bgn", label.minor = "setup")
## label step_major step_minor label_minor bgn end elapsed
## 1 fit.models_0_bgn 1 0 setup 45.883 NA NA
# load(paste0(glbOut$pfx, "dsk.RData"))
get_model_sel_frmla <- function() {
model_evl_terms <- c(NULL)
# min.aic.fit might not be avl
lclMdlEvlCriteria <-
glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)]
for (metric in lclMdlEvlCriteria)
model_evl_terms <- c(model_evl_terms,
ifelse(length(grep("max", metric)) > 0, "-", "+"), metric)
if (glb_is_classification && glb_is_binomial)
model_evl_terms <- c(model_evl_terms, "-", "opt.prob.threshold.OOB")
model_sel_frmla <- as.formula(paste(c("~ ", model_evl_terms), collapse = " "))
return(model_sel_frmla)
}
get_dsp_models_df <- function() {
dsp_models_cols <- c("id",
glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE))
dsp_models_df <-
#orderBy(get_model_sel_frmla(), glb_models_df)[, c("id", glbMdlMetricsEval)]
orderBy(get_model_sel_frmla(), glb_models_df)[, dsp_models_cols]
nCvMdl <- sapply(glb_models_lst, function(mdl) nrow(mdl$results))
nParams <- sapply(glb_models_lst, function(mdl) ifelse(mdl$method == "custom", 0,
nrow(subset(modelLookup(mdl$method), parameter != "parameter"))))
# nCvMdl <- nCvMdl[names(nCvMdl) != "avNNet"]
# nParams <- nParams[names(nParams) != "avNNet"]
if (length(cvMdlProblems <- nCvMdl[nCvMdl <= nParams]) > 0) {
print("Cross Validation issues:")
warning("Cross Validation issues:")
print(cvMdlProblems)
}
pltMdls <- setdiff(names(nCvMdl), names(cvMdlProblems))
pltMdls <- setdiff(pltMdls, names(nParams[nParams == 0]))
# length(pltMdls) == 21
png(paste0(glbOut$pfx, "bestTune.png"), width = 480 * 2, height = 480 * 4)
grid.newpage()
pushViewport(viewport(layout = grid.layout(ceiling(length(pltMdls) / 2.0), 2)))
pltIx <- 1
for (mdlId in pltMdls) {
print(ggplot(glb_models_lst[[mdlId]], highBestTune = TRUE) + labs(title = mdlId),
vp = viewport(layout.pos.row = ceiling(pltIx / 2.0),
layout.pos.col = ((pltIx - 1) %% 2) + 1))
pltIx <- pltIx + 1
}
dev.off()
if (all(row.names(dsp_models_df) != dsp_models_df$id))
row.names(dsp_models_df) <- dsp_models_df$id
return(dsp_models_df)
}
#get_dsp_models_df()
if (glb_is_classification && glb_is_binomial &&
(length(unique(glbObsFit[, glb_rsp_var])) < 2))
stop("glbObsFit$", glb_rsp_var, ": contains less than 2 unique values: ",
paste0(unique(glbObsFit[, glb_rsp_var]), collapse=", "))
max_cor_y_x_vars <- orderBy(~ -cor.y.abs,
subset(glb_feats_df, (exclude.as.feat == 0) & !nzv & !is.cor.y.abs.low &
is.na(cor.high.X)))[1:2, "id"]
max_cor_y_x_vars <- max_cor_y_x_vars[!is.na(max_cor_y_x_vars)]
if (length(max_cor_y_x_vars) < 2)
max_cor_y_x_vars <- union(max_cor_y_x_vars, ".pos")
if (!is.null(glb_Baseline_mdl_var)) {
if ((max_cor_y_x_vars[1] != glb_Baseline_mdl_var) &
(glb_feats_df[glb_feats_df$id == max_cor_y_x_vars[1], "cor.y.abs"] >
glb_feats_df[glb_feats_df$id == glb_Baseline_mdl_var, "cor.y.abs"]))
stop(max_cor_y_x_vars[1], " has a higher correlation with ", glb_rsp_var,
" than the Baseline var: ", glb_Baseline_mdl_var)
}
glb_model_type <- ifelse(glb_is_regression, "regression", "classification")
# Model specs
c("id.prefix", "method", "type",
# trainControl params
"preProc.method", "cv.n.folds", "cv.n.repeats", "summary.fn",
# train params
"metric", "metric.maximize", "tune.df")
## [1] "id.prefix" "method" "type"
## [4] "preProc.method" "cv.n.folds" "cv.n.repeats"
## [7] "summary.fn" "metric" "metric.maximize"
## [10] "tune.df"
# Baseline
if (!is.null(glb_Baseline_mdl_var)) {
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
paste0("fit.models_0_", "Baseline"), major.inc = FALSE,
label.minor = "mybaseln_classfr")
ret_lst <- myfit_mdl(mdl_id="Baseline",
model_method="mybaseln_classfr",
indep_vars_vctr=glb_Baseline_mdl_var,
rsp_var=glb_rsp_var,
fit_df=glbObsFit, OOB_df=glbObsOOB)
}
# Most Frequent Outcome "MFO" model: mean(y) for regression
# Not using caret's nullModel since model stats not avl
# Cannot use rpart for multinomial classification since it predicts non-MFO
if (glb_is_classification) {
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
paste0("fit.models_0_", "MFO"), major.inc = FALSE,
label.minor = "myMFO_classfr")
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = "MFO", type = glb_model_type, trainControl.method = "none",
train.method = ifelse(glb_is_regression, "lm", "myMFO_classfr"))),
indep_vars = ".rnorm", rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
# "random" model - only for classification;
# none needed for regression since it is same as MFO
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
paste0("fit.models_0_", "Random"), major.inc = FALSE,
label.minor = "myrandom_classfr")
#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = "Random", type = glb_model_type, trainControl.method = "none",
train.method = "myrandom_classfr")),
indep_vars = ".rnorm", rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
}
## label step_major step_minor label_minor bgn end
## 1 fit.models_0_bgn 1 0 setup 45.883 45.916
## 2 fit.models_0_MFO 1 1 myMFO_classfr 45.917 NA
## elapsed
## 1 0.034
## 2 NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: MFO###myMFO_classfr"
## [1] " indep_vars: .rnorm"
## [1] "myfit_mdl: setup complete: 0.720000 secs"
## Fitting parameter = none on full training set
## [1] "in MFO.Classifier$fit"
## [1] "unique.vals:"
## [1] N Y
## Levels: N Y
## [1] "unique.prob:"
## y
## Y N
## 0.5014985 0.4985015
## [1] "MFO.val:"
## [1] "Y"
## [1] "myfit_mdl: train complete: 1.124000 secs"
## Length Class Mode
## unique.vals 2 factor numeric
## unique.prob 2 -none- numeric
## MFO.val 1 -none- character
## x.names 1 -none- character
## xNames 1 -none- character
## problemType 1 -none- character
## tuneValue 1 data.frame list
## obsLevels 2 -none- character
## [1] "myfit_mdl: train diagnostics complete: 1.126000 secs"
## Loading required namespace: pROC
## [1] "entr MFO.Classifier$predict"
## [1] "exit MFO.Classifier$predict"
## Loading required package: ROCR
## Loading required package: gplots
##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess
## [1] "in MFO.Classifier$prob"
## N Y
## 1 0.5014985 0.4985015
## 2 0.5014985 0.4985015
## 3 0.5014985 0.4985015
## 4 0.5014985 0.4985015
## 5 0.5014985 0.4985015
## 6 0.5014985 0.4985015
## Prediction
## Reference N Y
## N 0 499
## Y 0 502
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.014985e-01 0.000000e+00 4.700593e-01 5.329288e-01 5.014985e-01
## AccuracyPValue McnemarPValue
## 5.126189e-01 4.268523e-110
## [1] "entr MFO.Classifier$predict"
## [1] "exit MFO.Classifier$predict"
## [1] "in MFO.Classifier$prob"
## N Y
## 1 0.5014985 0.4985015
## 2 0.5014985 0.4985015
## 3 0.5014985 0.4985015
## 4 0.5014985 0.4985015
## 5 0.5014985 0.4985015
## 6 0.5014985 0.4985015
## Prediction
## Reference N Y
## N 0 498
## Y 0 501
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.015015e-01 0.000000e+00 4.700304e-01 5.329637e-01 5.015015e-01
## AccuracyPValue McnemarPValue
## 5.126315e-01 7.044652e-110
## [1] "myfit_mdl: predict complete: 3.322000 secs"
## id feats max.nTuningRuns min.elapsedtime.everything
## 1 MFO###myMFO_classfr .rnorm 0 0.397
## min.elapsedtime.final max.AUCpROC.fit max.Sens.fit max.Spec.fit
## 1 0.004 0.5 0 1
## max.AUCROCR.fit opt.prob.threshold.fit max.f.score.fit max.Accuracy.fit
## 1 0.5 0.4 0.6679973 0.5014985
## max.AccuracyLower.fit max.AccuracyUpper.fit max.Kappa.fit
## 1 0.4700593 0.5329288 0
## max.AUCpROC.OOB max.Sens.OOB max.Spec.OOB max.AUCROCR.OOB
## 1 0.5 0 1 0.5
## opt.prob.threshold.OOB max.f.score.OOB max.Accuracy.OOB
## 1 0.4 0.668 0.5015015
## max.AccuracyLower.OOB max.AccuracyUpper.OOB max.Kappa.OOB
## 1 0.4700304 0.5329637 0
## [1] "myfit_mdl: exit: 3.332000 secs"
## label step_major step_minor label_minor bgn end
## 2 fit.models_0_MFO 1 1 myMFO_classfr 45.917 49.254
## 3 fit.models_0_Random 1 2 myrandom_classfr 49.255 NA
## elapsed
## 2 3.337
## 3 NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Random###myrandom_classfr"
## [1] " indep_vars: .rnorm"
## [1] "myfit_mdl: setup complete: 0.436000 secs"
## Fitting parameter = none on full training set
## [1] "myfit_mdl: train complete: 0.699000 secs"
## Length Class Mode
## unique.vals 2 factor numeric
## unique.prob 2 table numeric
## xNames 1 -none- character
## problemType 1 -none- character
## tuneValue 1 data.frame list
## obsLevels 2 -none- character
## [1] "myfit_mdl: train diagnostics complete: 0.700000 secs"
## [1] "in Random.Classifier$prob"
## Prediction
## Reference N Y
## N 0 499
## Y 0 502
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.014985e-01 0.000000e+00 4.700593e-01 5.329288e-01 5.014985e-01
## AccuracyPValue McnemarPValue
## 5.126189e-01 4.268523e-110
## [1] "in Random.Classifier$prob"
## Prediction
## Reference N Y
## N 0 498
## Y 0 501
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.015015e-01 0.000000e+00 4.700304e-01 5.329637e-01 5.015015e-01
## AccuracyPValue McnemarPValue
## 5.126315e-01 7.044652e-110
## [1] "myfit_mdl: predict complete: 2.936000 secs"
## id feats max.nTuningRuns
## 1 Random###myrandom_classfr .rnorm 0
## min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1 0.26 0.001 0.4945369
## max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1 0.50501 0.4840637 0.4764948 0.4
## max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1 0.6679973 0.5014985 0.4700593
## max.AccuracyUpper.fit max.Kappa.fit max.AUCpROC.OOB max.Sens.OOB
## 1 0.5329288 0 0.505471 0.4939759
## max.Spec.OOB max.AUCROCR.OOB opt.prob.threshold.OOB max.f.score.OOB
## 1 0.5169661 0.4974749 0.4 0.668
## max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1 0.5015015 0.4700304 0.5329637
## max.Kappa.OOB
## 1 0
## [1] "myfit_mdl: exit: 2.948000 secs"
# Max.cor.Y
# Check impact of cv
# rpart is not a good candidate since caret does not optimize cp (only tuning parameter of rpart) well
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
paste0("fit.models_0_", "Max.cor.Y.rcv.*X*"), major.inc = FALSE,
label.minor = "glmnet")
## label step_major step_minor label_minor
## 3 fit.models_0_Random 1 2 myrandom_classfr
## 4 fit.models_0_Max.cor.Y.rcv.*X* 1 3 glmnet
## bgn end elapsed
## 3 49.255 52.214 2.959
## 4 52.215 NA NA
ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
id.prefix="Max.cor.Y.rcv.1X1", type=glb_model_type, trainControl.method="none",
train.method="glmnet")),
indep_vars=max_cor_y_x_vars, rsp_var=glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.001000 secs"
## [1] "fitting model: Max.cor.Y.rcv.1X1###glmnet"
## [1] " indep_vars: .pos,.rnorm"
## [1] "myfit_mdl: setup complete: 0.699000 secs"
## Loading required package: glmnet
## Loading required package: Matrix
## Loaded glmnet 2.0-2
## Fitting alpha = 0.1, lambda = 0.000301 on full training set
## [1] "myfit_mdl: train complete: 1.410000 secs"
## Length Class Mode
## a0 21 -none- numeric
## beta 42 dgCMatrix S4
## df 21 -none- numeric
## dim 2 -none- numeric
## lambda 21 -none- numeric
## dev.ratio 21 -none- numeric
## nulldev 1 -none- numeric
## npasses 1 -none- numeric
## jerr 1 -none- numeric
## offset 1 -none- logical
## classnames 2 -none- character
## call 5 -none- call
## nobs 1 -none- numeric
## lambdaOpt 1 -none- numeric
## xNames 2 -none- character
## problemType 1 -none- character
## tuneValue 2 data.frame list
## obsLevels 2 -none- character
## [1] "min lambda > lambdaOpt:"
## (Intercept) .pos .rnorm
## -7.411840e-02 7.971822e-05 2.394875e-02
## [1] "max lambda < lambdaOpt:"
## [1] "Feats mismatch between coefs_left & rght:"
## [1] "(Intercept)" ".pos" ".rnorm"
## [1] "myfit_mdl: train diagnostics complete: 1.510000 secs"
## Prediction
## Reference N Y
## N 0 499
## Y 0 502
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.014985e-01 0.000000e+00 4.700593e-01 5.329288e-01 5.014985e-01
## AccuracyPValue McnemarPValue
## 5.126189e-01 4.268523e-110
## Prediction
## Reference N Y
## N 0 498
## Y 0 501
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.015015e-01 0.000000e+00 4.700304e-01 5.329637e-01 5.015015e-01
## AccuracyPValue McnemarPValue
## 5.126315e-01 7.044652e-110
## [1] "myfit_mdl: predict complete: 4.156000 secs"
## id feats max.nTuningRuns
## 1 Max.cor.Y.rcv.1X1###glmnet .pos,.rnorm 0
## min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1 0.707 0.013 0.5193475
## max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1 0.4749499 0.563745 0.5191738 0.4
## max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1 0.6679973 0.5014985 0.4700593
## max.AccuracyUpper.fit max.Kappa.fit max.AUCpROC.OOB max.Sens.OOB
## 1 0.5329288 0 0.5174771 0.5040161
## max.Spec.OOB max.AUCROCR.OOB opt.prob.threshold.OOB max.f.score.OOB
## 1 0.5309381 0.5082125 0.4 0.668
## max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1 0.5015015 0.4700304 0.5329637
## max.Kappa.OOB
## 1 0
## [1] "myfit_mdl: exit: 4.169000 secs"
if (glbMdlCheckRcv) {
# rcv_n_folds == 1 & rcv_n_repeats > 1 crashes
for (rcv_n_folds in seq(3, glb_rcv_n_folds + 2, 2))
for (rcv_n_repeats in seq(1, glb_rcv_n_repeats + 2, 2)) {
# Experiment specific code to avoid caret crash
# lcl_tune_models_df <- rbind(data.frame()
# ,data.frame(method = "glmnet", parameter = "alpha",
# vals = "0.100 0.325 0.550 0.775 1.000")
# ,data.frame(method = "glmnet", parameter = "lambda",
# vals = "9.342e-02")
# )
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst =
list(
id.prefix = paste0("Max.cor.Y.rcv.", rcv_n_folds, "X", rcv_n_repeats),
type = glb_model_type,
# tune.df = lcl_tune_models_df,
trainControl.method = "repeatedcv",
trainControl.number = rcv_n_folds,
trainControl.repeats = rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
train.method = "glmnet", train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize)),
indep_vars = max_cor_y_x_vars, rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
}
# Add parallel coordinates graph of glb_models_df[, glbMdlMetricsEval] to evaluate cv parameters
tmp_models_cols <- c("id", "max.nTuningRuns",
glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE))
print(myplot_parcoord(obs_df = subset(glb_models_df,
grepl("Max.cor.Y.rcv.", id, fixed = TRUE),
select = -feats)[, tmp_models_cols],
id_var = "id"))
}
# Useful for stacking decisions
# fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
# paste0("fit.models_0_", "Max.cor.Y[rcv.1X1.cp.0|]"), major.inc = FALSE,
# label.minor = "rpart")
#
# ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
# id.prefix = "Max.cor.Y.rcv.1X1.cp.0", type = glb_model_type, trainControl.method = "none",
# train.method = "rpart",
# tune.df=data.frame(method="rpart", parameter="cp", min=0.0, max=0.0, by=0.1))),
# indep_vars=max_cor_y_x_vars, rsp_var=glb_rsp_var,
# fit_df=glbObsFit, OOB_df=glbObsOOB)
#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)
# if (glb_is_regression || glb_is_binomial) # For multinomials this model will be run next by default
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = "Max.cor.Y",
type = glb_model_type, trainControl.method = "repeatedcv",
trainControl.number = glb_rcv_n_folds,
trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
trainControl.allowParallel = glbMdlAllowParallel,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = "rpart")),
indep_vars = max_cor_y_x_vars, rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Max.cor.Y##rcv#rpart"
## [1] " indep_vars: .pos,.rnorm"
## [1] "myfit_mdl: setup complete: 0.996000 secs"
## Loading required package: rpart
## Aggregating results
## Selecting tuning parameters
## Fitting cp = 0.00601 on full training set
## [1] "myfit_mdl: train complete: 2.664000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = "Max.cor.Y", : model's bestTune found at an extreme of
## tuneGrid for parameter: cp
## Loading required package: rpart.plot
## Call:
## rpart(formula = .outcome ~ ., control = list(minsplit = 20, minbucket = 7,
## cp = 0, maxcompete = 4, maxsurrogate = 5, usesurrogate = 2,
## surrogatestyle = 0, maxdepth = 30, xval = 0))
## n= 1001
##
## CP nsplit rel error
## 1 0.036072144 0 1.0000000
## 2 0.013627255 1 0.9639279
## 3 0.012024048 6 0.8957916
## 4 0.008016032 16 0.7615230
## 5 0.006012024 18 0.7454910
##
## Variable importance
## .pos .rnorm
## 60 40
##
## Node number 1: 1001 observations, complexity param=0.03607214
## predicted class=Y expected loss=0.4985015 P(node) =1
## class counts: 499 502
## probabilities: 0.499 0.501
## left son=2 (940 obs) right son=3 (61 obs)
## Primary splits:
## .pos < 1879.5 to the left, improve=3.782599, (0 missing)
## .rnorm < 0.9109794 to the left, improve=1.411298, (0 missing)
##
## Node number 2: 940 observations, complexity param=0.01362725
## predicted class=N expected loss=0.4904255 P(node) =0.9390609
## class counts: 479 461
## probabilities: 0.510 0.490
## left son=4 (24 obs) right son=5 (916 obs)
## Primary splits:
## .pos < 49.5 to the left, improve=2.847310, (0 missing)
## .rnorm < -2.042758 to the left, improve=1.336671, (0 missing)
##
## Node number 3: 61 observations
## predicted class=Y expected loss=0.3278689 P(node) =0.06093906
## class counts: 20 41
## probabilities: 0.328 0.672
##
## Node number 4: 24 observations
## predicted class=N expected loss=0.25 P(node) =0.02397602
## class counts: 18 6
## probabilities: 0.750 0.250
##
## Node number 5: 916 observations, complexity param=0.01362725
## predicted class=N expected loss=0.4967249 P(node) =0.9150849
## class counts: 461 455
## probabilities: 0.503 0.497
## left son=10 (15 obs) right son=11 (901 obs)
## Primary splits:
## .pos < 1851 to the right, improve=2.685344, (0 missing)
## .rnorm < -2.042758 to the left, improve=1.437132, (0 missing)
##
## Node number 10: 15 observations
## predicted class=N expected loss=0.2 P(node) =0.01498501
## class counts: 12 3
## probabilities: 0.800 0.200
##
## Node number 11: 901 observations, complexity param=0.01362725
## predicted class=Y expected loss=0.4983352 P(node) =0.9000999
## class counts: 449 452
## probabilities: 0.498 0.502
## left son=22 (832 obs) right son=23 (69 obs)
## Primary splits:
## .pos < 1722 to the left, improve=1.279739, (0 missing)
## .rnorm < -2.04591 to the left, improve=1.218490, (0 missing)
##
## Node number 22: 832 observations, complexity param=0.01362725
## predicted class=N expected loss=0.4939904 P(node) =0.8311688
## class counts: 421 411
## probabilities: 0.506 0.494
## left son=44 (72 obs) right son=45 (760 obs)
## Primary splits:
## .pos < 1561.5 to the right, improve=2.232009, (0 missing)
## .rnorm < 0.9109794 to the left, improve=1.492223, (0 missing)
##
## Node number 23: 69 observations, complexity param=0.008016032
## predicted class=Y expected loss=0.4057971 P(node) =0.06893107
## class counts: 28 41
## probabilities: 0.406 0.594
## left son=46 (8 obs) right son=47 (61 obs)
## Primary splits:
## .rnorm < 1.567178 to the right, improve=2.144215, (0 missing)
## .pos < 1797.5 to the right, improve=1.059146, (0 missing)
##
## Node number 44: 72 observations
## predicted class=N expected loss=0.375 P(node) =0.07192807
## class counts: 45 27
## probabilities: 0.625 0.375
##
## Node number 45: 760 observations, complexity param=0.01362725
## predicted class=Y expected loss=0.4947368 P(node) =0.7592408
## class counts: 376 384
## probabilities: 0.495 0.505
## left son=90 (633 obs) right son=91 (127 obs)
## Primary splits:
## .rnorm < 0.9109794 to the left, improve=1.8276070, (0 missing)
## .pos < 1467 to the left, improve=0.8535928, (0 missing)
##
## Node number 46: 8 observations
## predicted class=N expected loss=0.25 P(node) =0.007992008
## class counts: 6 2
## probabilities: 0.750 0.250
##
## Node number 47: 61 observations
## predicted class=Y expected loss=0.3606557 P(node) =0.06093906
## class counts: 22 39
## probabilities: 0.361 0.639
##
## Node number 90: 633 observations, complexity param=0.01202405
## predicted class=N expected loss=0.4897314 P(node) =0.6323676
## class counts: 323 310
## probabilities: 0.510 0.490
## left son=180 (8 obs) right son=181 (625 obs)
## Primary splits:
## .rnorm < 0.886005 to the right, improve=3.886509, (0 missing)
## .pos < 1467 to the left, improve=2.033433, (0 missing)
##
## Node number 91: 127 observations, complexity param=0.01202405
## predicted class=Y expected loss=0.4173228 P(node) =0.1268731
## class counts: 53 74
## probabilities: 0.417 0.583
## left son=182 (34 obs) right son=183 (93 obs)
## Primary splits:
## .rnorm < 1.661505 to the right, improve=2.712546, (0 missing)
## .pos < 1497 to the right, improve=2.517075, (0 missing)
## Surrogate splits:
## .pos < 1546.5 to the right, agree=0.74, adj=0.029, (0 split)
##
## Node number 180: 8 observations
## predicted class=N expected loss=0 P(node) =0.007992008
## class counts: 8 0
## probabilities: 1.000 0.000
##
## Node number 181: 625 observations, complexity param=0.01202405
## predicted class=N expected loss=0.496 P(node) =0.6243756
## class counts: 315 310
## probabilities: 0.504 0.496
## left son=362 (581 obs) right son=363 (44 obs)
## Primary splits:
## .pos < 1467 to the left, improve=1.865073, (0 missing)
## .rnorm < 0.8086129 to the left, improve=1.045640, (0 missing)
##
## Node number 182: 34 observations
## predicted class=N expected loss=0.4117647 P(node) =0.03396603
## class counts: 20 14
## probabilities: 0.588 0.412
##
## Node number 183: 93 observations
## predicted class=Y expected loss=0.3548387 P(node) =0.09290709
## class counts: 33 60
## probabilities: 0.355 0.645
##
## Node number 362: 581 observations, complexity param=0.01202405
## predicted class=N expected loss=0.4853701 P(node) =0.5804196
## class counts: 299 282
## probabilities: 0.515 0.485
## left son=724 (65 obs) right son=725 (516 obs)
## Primary splits:
## .pos < 1309.5 to the right, improve=1.974368, (0 missing)
## .rnorm < 0.8086129 to the left, improve=1.136108, (0 missing)
## Surrogate splits:
## .rnorm < 0.8475129 to the right, agree=0.89, adj=0.015, (0 split)
##
## Node number 363: 44 observations
## predicted class=Y expected loss=0.3636364 P(node) =0.04395604
## class counts: 16 28
## probabilities: 0.364 0.636
##
## Node number 724: 65 observations
## predicted class=N expected loss=0.3692308 P(node) =0.06493506
## class counts: 41 24
## probabilities: 0.631 0.369
##
## Node number 725: 516 observations, complexity param=0.01202405
## predicted class=N expected loss=0.5 P(node) =0.5154845
## class counts: 258 258
## probabilities: 0.500 0.500
## left son=1450 (505 obs) right son=1451 (11 obs)
## Primary splits:
## .rnorm < 0.7824803 to the left, improve=1.161116, (0 missing)
## .pos < 778 to the left, improve=1.138786, (0 missing)
##
## Node number 1450: 505 observations, complexity param=0.01202405
## predicted class=N expected loss=0.4950495 P(node) =0.5044955
## class counts: 255 250
## probabilities: 0.505 0.495
## left son=2900 (284 obs) right son=2901 (221 obs)
## Primary splits:
## .pos < 778 to the left, improve=1.188523, (0 missing)
## .rnorm < 0.5988531 to the right, improve=1.051388, (0 missing)
## Surrogate splits:
## .rnorm < -2.594986 to the right, agree=0.566, adj=0.009, (0 split)
##
## Node number 1451: 11 observations
## predicted class=Y expected loss=0.2727273 P(node) =0.01098901
## class counts: 3 8
## probabilities: 0.273 0.727
##
## Node number 2900: 284 observations, complexity param=0.01202405
## predicted class=N expected loss=0.4647887 P(node) =0.2837163
## class counts: 152 132
## probabilities: 0.535 0.465
## left son=5800 (34 obs) right son=5801 (250 obs)
## Primary splits:
## .pos < 682 to the right, improve=4.068481, (0 missing)
## .rnorm < 0.7025789 to the right, improve=1.093754, (0 missing)
##
## Node number 2901: 221 observations, complexity param=0.01202405
## predicted class=Y expected loss=0.4660633 P(node) =0.2207792
## class counts: 103 118
## probabilities: 0.466 0.534
## left son=5802 (54 obs) right son=5803 (167 obs)
## Primary splits:
## .rnorm < -0.6868919 to the left, improve=1.667375, (0 missing)
## .pos < 831.5 to the right, improve=1.509522, (0 missing)
## Surrogate splits:
## .pos < 782.5 to the left, agree=0.76, adj=0.019, (0 split)
##
## Node number 5800: 34 observations
## predicted class=N expected loss=0.2352941 P(node) =0.03396603
## class counts: 26 8
## probabilities: 0.765 0.235
##
## Node number 5801: 250 observations, complexity param=0.01202405
## predicted class=N expected loss=0.496 P(node) =0.2497502
## class counts: 126 124
## probabilities: 0.504 0.496
## left son=11602 (157 obs) right son=11603 (93 obs)
## Primary splits:
## .rnorm < -0.6135509 to the right, improve=1.617163, (0 missing)
## .pos < 534 to the left, improve=1.430893, (0 missing)
##
## Node number 5802: 54 observations
## predicted class=N expected loss=0.4259259 P(node) =0.05394605
## class counts: 31 23
## probabilities: 0.574 0.426
##
## Node number 5803: 167 observations, complexity param=0.008016032
## predicted class=Y expected loss=0.4311377 P(node) =0.1668332
## class counts: 72 95
## probabilities: 0.431 0.569
## left son=11606 (38 obs) right son=11607 (129 obs)
## Primary splits:
## .rnorm < 0.3613548 to the right, improve=1.452275, (0 missing)
## .pos < 865.5 to the right, improve=1.171194, (0 missing)
## Surrogate splits:
## .pos < 1304.5 to the right, agree=0.778, adj=0.026, (0 split)
##
## Node number 11602: 157 observations, complexity param=0.01202405
## predicted class=N expected loss=0.4522293 P(node) =0.1568432
## class counts: 86 71
## probabilities: 0.548 0.452
## left son=23204 (119 obs) right son=23205 (38 obs)
## Primary splits:
## .pos < 534.5 to the left, improve=2.348234, (0 missing)
## .rnorm < 0.3687223 to the left, improve=1.967046, (0 missing)
##
## Node number 11603: 93 observations
## predicted class=Y expected loss=0.4301075 P(node) =0.09290709
## class counts: 40 53
## probabilities: 0.430 0.570
##
## Node number 11606: 38 observations
## predicted class=N expected loss=0.4473684 P(node) =0.03796204
## class counts: 21 17
## probabilities: 0.553 0.447
##
## Node number 11607: 129 observations
## predicted class=Y expected loss=0.3953488 P(node) =0.1288711
## class counts: 51 78
## probabilities: 0.395 0.605
##
## Node number 23204: 119 observations
## predicted class=N expected loss=0.4033613 P(node) =0.1188811
## class counts: 71 48
## probabilities: 0.597 0.403
##
## Node number 23205: 38 observations
## predicted class=Y expected loss=0.3947368 P(node) =0.03796204
## class counts: 15 23
## probabilities: 0.395 0.605
##
## n= 1001
##
## node), split, n, loss, yval, (yprob)
## * denotes terminal node
##
## 1) root 1001 499 Y (0.4985015 0.5014985)
## 2) .pos< 1879.5 940 461 N (0.5095745 0.4904255)
## 4) .pos< 49.5 24 6 N (0.7500000 0.2500000) *
## 5) .pos>=49.5 916 455 N (0.5032751 0.4967249)
## 10) .pos>=1851 15 3 N (0.8000000 0.2000000) *
## 11) .pos< 1851 901 449 Y (0.4983352 0.5016648)
## 22) .pos< 1722 832 411 N (0.5060096 0.4939904)
## 44) .pos>=1561.5 72 27 N (0.6250000 0.3750000) *
## 45) .pos< 1561.5 760 376 Y (0.4947368 0.5052632)
## 90) .rnorm< 0.9109794 633 310 N (0.5102686 0.4897314)
## 180) .rnorm>=0.886005 8 0 N (1.0000000 0.0000000) *
## 181) .rnorm< 0.886005 625 310 N (0.5040000 0.4960000)
## 362) .pos< 1467 581 282 N (0.5146299 0.4853701)
## 724) .pos>=1309.5 65 24 N (0.6307692 0.3692308) *
## 725) .pos< 1309.5 516 258 N (0.5000000 0.5000000)
## 1450) .rnorm< 0.7824803 505 250 N (0.5049505 0.4950495)
## 2900) .pos< 778 284 132 N (0.5352113 0.4647887)
## 5800) .pos>=682 34 8 N (0.7647059 0.2352941) *
## 5801) .pos< 682 250 124 N (0.5040000 0.4960000)
## 11602) .rnorm>=-0.6135509 157 71 N (0.5477707 0.4522293)
## 23204) .pos< 534.5 119 48 N (0.5966387 0.4033613) *
## 23205) .pos>=534.5 38 15 Y (0.3947368 0.6052632) *
## 11603) .rnorm< -0.6135509 93 40 Y (0.4301075 0.5698925) *
## 2901) .pos>=778 221 103 Y (0.4660633 0.5339367)
## 5802) .rnorm< -0.6868919 54 23 N (0.5740741 0.4259259) *
## 5803) .rnorm>=-0.6868919 167 72 Y (0.4311377 0.5688623)
## 11606) .rnorm>=0.3613548 38 17 N (0.5526316 0.4473684) *
## 11607) .rnorm< 0.3613548 129 51 Y (0.3953488 0.6046512) *
## 1451) .rnorm>=0.7824803 11 3 Y (0.2727273 0.7272727) *
## 363) .pos>=1467 44 16 Y (0.3636364 0.6363636) *
## 91) .rnorm>=0.9109794 127 53 Y (0.4173228 0.5826772)
## 182) .rnorm>=1.661505 34 14 N (0.5882353 0.4117647) *
## 183) .rnorm< 1.661505 93 33 Y (0.3548387 0.6451613) *
## 23) .pos>=1722 69 28 Y (0.4057971 0.5942029)
## 46) .rnorm>=1.567178 8 2 N (0.7500000 0.2500000) *
## 47) .rnorm< 1.567178 61 22 Y (0.3606557 0.6393443) *
## 3) .pos>=1879.5 61 20 Y (0.3278689 0.6721311) *
## [1] "myfit_mdl: train diagnostics complete: 3.838000 secs"
## Prediction
## Reference N Y
## N 70 429
## Y 19 483
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.524476e-01 1.026841e-01 5.210284e-01 5.835573e-01 5.014985e-01
## AccuracyPValue McnemarPValue
## 6.990030e-04 3.411826e-83
## Prediction
## Reference N Y
## N 0 498
## Y 0 501
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.015015e-01 0.000000e+00 4.700304e-01 5.329637e-01 5.015015e-01
## AccuracyPValue McnemarPValue
## 5.126315e-01 7.044652e-110
## [1] "myfit_mdl: predict complete: 5.820000 secs"
## id feats max.nTuningRuns
## 1 Max.cor.Y##rcv#rpart .pos,.rnorm 5
## min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1 1.663 0.016 0.6282845
## max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1 0.5991984 0.6573705 0.6561609 0.3
## max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1 0.6831683 0.5098352 0.5210284
## max.AccuracyUpper.fit max.Kappa.fit max.AUCpROC.OOB max.Sens.OOB
## 1 0.5835573 0.01961675 0.5005952 0.5321285
## max.Spec.OOB max.AUCROCR.OOB opt.prob.threshold.OOB max.f.score.OOB
## 1 0.4690619 0.4868235 0 0.668
## max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1 0.5015015 0.4700304 0.5329637
## max.Kappa.OOB max.AccuracySD.fit max.KappaSD.fit
## 1 0 0.02434529 0.0485855
## [1] "myfit_mdl: exit: 5.836000 secs"
if ((length(glbFeatsDateTime) > 0) &&
(sum(grepl(paste(names(glbFeatsDateTime), "\\.day\\.minutes\\.poly\\.", sep = ""),
names(glbObsAll))) > 0)) {
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
paste0("fit.models_0_", "Max.cor.Y.Time.Poly"), major.inc = FALSE,
label.minor = "glmnet")
indepVars <- c(max_cor_y_x_vars,
grep(paste(names(glbFeatsDateTime), "\\.day\\.minutes\\.poly\\.", sep = ""),
names(glbObsAll), value = TRUE))
indepVars <- myadjust_interaction_feats(indepVars)
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = "Max.cor.Y.Time.Poly",
type = glb_model_type, trainControl.method = "repeatedcv",
trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = "glmnet")),
indep_vars = indepVars,
rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
}
if ((length(glbFeatsDateTime) > 0) &&
(sum(grepl(paste(names(glbFeatsDateTime), "\\.last[[:digit:]]", sep = ""),
names(glbObsAll))) > 0)) {
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
paste0("fit.models_0_", "Max.cor.Y.Time.Lag"), major.inc = FALSE,
label.minor = "glmnet")
indepVars <- c(max_cor_y_x_vars,
grep(paste(names(glbFeatsDateTime), "\\.last[[:digit:]]", sep = ""),
names(glbObsAll), value = TRUE))
indepVars <- myadjust_interaction_feats(indepVars)
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = "Max.cor.Y.Time.Lag",
type = glb_model_type,
tune.df = glbMdlTuneParams,
trainControl.method = "repeatedcv",
trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = "glmnet")),
indep_vars = indepVars,
rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
}
if (length(glbFeatsText) > 0) {
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
paste0("fit.models_0_", "Txt.*"), major.inc = FALSE,
label.minor = "glmnet")
indepVars <- c(max_cor_y_x_vars)
for (txtFeat in names(glbFeatsText))
indepVars <- union(indepVars,
grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.(?!([T|P]\\.))", sep = ""),
names(glbObsAll), perl = TRUE, value = TRUE))
indepVars <- myadjust_interaction_feats(indepVars)
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = "Max.cor.Y.Text.nonTP",
type = glb_model_type,
tune.df = glbMdlTuneParams,
trainControl.method = "repeatedcv",
trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
trainControl.allowParallel = glbMdlAllowParallel,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = "glmnet")),
indep_vars = indepVars,
rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
indepVars <- c(max_cor_y_x_vars)
for (txtFeat in names(glbFeatsText))
indepVars <- union(indepVars,
grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.T\\.", sep = ""),
names(glbObsAll), perl = TRUE, value = TRUE))
indepVars <- myadjust_interaction_feats(indepVars)
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = "Max.cor.Y.Text.onlyT",
type = glb_model_type,
tune.df = glbMdlTuneParams,
trainControl.method = "repeatedcv",
trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = "glmnet")),
indep_vars = indepVars,
rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
indepVars <- c(max_cor_y_x_vars)
for (txtFeat in names(glbFeatsText))
indepVars <- union(indepVars,
grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.P\\.", sep = ""),
names(glbObsAll), perl = TRUE, value = TRUE))
indepVars <- myadjust_interaction_feats(indepVars)
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = "Max.cor.Y.Text.onlyP",
type = glb_model_type,
tune.df = glbMdlTuneParams,
trainControl.method = "repeatedcv",
trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
trainControl.allowParallel = glbMdlAllowParallel,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = "glmnet")),
indep_vars = indepVars,
rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
}
# Interactions.High.cor.Y
if (length(int_feats <- setdiff(setdiff(unique(glb_feats_df$cor.high.X), NA),
subset(glb_feats_df, nzv)$id)) > 0) {
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
paste0("fit.models_0_", "Interact.High.cor.Y"), major.inc = FALSE,
label.minor = "glmnet")
ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
id.prefix="Interact.High.cor.Y",
type=glb_model_type, trainControl.method="repeatedcv",
trainControl.number=glb_rcv_n_folds, trainControl.repeats=glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
trainControl.allowParallel = glbMdlAllowParallel,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method="glmnet")),
indep_vars=c(max_cor_y_x_vars, paste(max_cor_y_x_vars[1], int_feats, sep=":")),
rsp_var=glb_rsp_var,
fit_df=glbObsFit, OOB_df=glbObsOOB)
}
# Low.cor.X
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df,
paste0("fit.models_0_", "Low.cor.X"), major.inc = FALSE,
label.minor = "glmnet")
## label step_major step_minor label_minor bgn
## 4 fit.models_0_Max.cor.Y.rcv.*X* 1 3 glmnet 52.215
## 5 fit.models_0_Low.cor.X 1 4 glmnet 62.291
## end elapsed
## 4 62.291 10.076
## 5 NA NA
indep_vars <- subset(glb_feats_df, is.na(cor.high.X) & !nzv &
(exclude.as.feat != 1))[, "id"]
indep_vars <- myadjust_interaction_feats(indep_vars)
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = "Low.cor.X",
type = glb_model_type,
tune.df = glbMdlTuneParams,
trainControl.method = "repeatedcv",
trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
trainControl.allowParallel = glbMdlAllowParallel,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = "glmnet")),
indep_vars = indep_vars, rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Low.cor.X##rcv#glmnet"
## [1] " indep_vars: .pos,.rnorm"
## [1] "myfit_mdl: setup complete: 0.716000 secs"
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 0.325, lambda = 0.00649 on full training set
## [1] "myfit_mdl: train complete: 2.633000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = "Low.cor.X", : model's bestTune found at an extreme of
## tuneGrid for parameter: lambda
## Length Class Mode
## a0 20 -none- numeric
## beta 40 dgCMatrix S4
## df 20 -none- numeric
## dim 2 -none- numeric
## lambda 20 -none- numeric
## dev.ratio 20 -none- numeric
## nulldev 1 -none- numeric
## npasses 1 -none- numeric
## jerr 1 -none- numeric
## offset 1 -none- logical
## classnames 2 -none- character
## call 5 -none- call
## nobs 1 -none- numeric
## lambdaOpt 1 -none- numeric
## xNames 2 -none- character
## problemType 1 -none- character
## tuneValue 2 data.frame list
## obsLevels 2 -none- character
## [1] "min lambda > lambdaOpt:"
## (Intercept) .pos .rnorm
## -7.747964e-02 8.305337e-05 2.446781e-02
## [1] "max lambda < lambdaOpt:"
## [1] "Feats mismatch between coefs_left & rght:"
## [1] "(Intercept)" ".pos" ".rnorm"
## [1] "myfit_mdl: train diagnostics complete: 3.216000 secs"
## Prediction
## Reference N Y
## N 0 499
## Y 0 502
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.014985e-01 0.000000e+00 4.700593e-01 5.329288e-01 5.014985e-01
## AccuracyPValue McnemarPValue
## 5.126189e-01 4.268523e-110
## Prediction
## Reference N Y
## N 0 498
## Y 0 501
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.015015e-01 0.000000e+00 4.700304e-01 5.329637e-01 5.015015e-01
## AccuracyPValue McnemarPValue
## 5.126315e-01 7.044652e-110
## [1] "myfit_mdl: predict complete: 5.860000 secs"
## id feats max.nTuningRuns
## 1 Low.cor.X##rcv#glmnet .pos,.rnorm 15
## min.elapsedtime.everything min.elapsedtime.final max.AUCpROC.fit
## 1 1.913 0.008 0.5203614
## max.Sens.fit max.Spec.fit max.AUCROCR.fit opt.prob.threshold.fit
## 1 0.4809619 0.559761 0.5192057 0.4
## max.f.score.fit max.Accuracy.fit max.AccuracyLower.fit
## 1 0.6679973 0.5008332 0.4700593
## max.AccuracyUpper.fit max.Kappa.fit max.AUCpROC.OOB max.Sens.OOB
## 1 0.5329288 0.001520074 0.5164731 0.502008
## max.Spec.OOB max.AUCROCR.OOB opt.prob.threshold.OOB max.f.score.OOB
## 1 0.5309381 0.508453 0.4 0.668
## max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1 0.5015015 0.4700304 0.5329637
## max.Kappa.OOB max.AccuracySD.fit max.KappaSD.fit
## 1 0 0.02299258 0.04598811
## [1] "myfit_mdl: exit: 5.875000 secs"
fit.models_0_chunk_df <-
myadd_chunk(fit.models_0_chunk_df, "fit.models_0_end", major.inc = FALSE,
label.minor = "teardown")
## label step_major step_minor label_minor bgn end
## 5 fit.models_0_Low.cor.X 1 4 glmnet 62.291 68.216
## 6 fit.models_0_end 1 5 teardown 68.217 NA
## elapsed
## 5 5.925
## 6 NA
rm(ret_lst)
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc = FALSE)
## label step_major step_minor label_minor bgn end elapsed
## 16 fit.models 8 0 0 45.382 68.23 22.848
## 17 fit.models 8 1 1 68.231 NA NA
fit.models_1_chunk_df <- myadd_chunk(NULL, "fit.models_1_bgn", label.minor = "setup")
## label step_major step_minor label_minor bgn end elapsed
## 1 fit.models_1_bgn 1 0 setup 71.719 NA NA
# refactor code for outliers / ensure all model runs exclude outliers in this chunk ???
#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)
topindep_var <- NULL; interact_vars <- NULL;
for (mdl_id_pfx in names(glbMdlFamilies)) {
fit.models_1_chunk_df <-
myadd_chunk(fit.models_1_chunk_df, paste0("fit.models_1_", mdl_id_pfx),
major.inc = FALSE, label.minor = "setup")
indep_vars <- NULL;
if (grepl("\\.Interact", mdl_id_pfx)) {
if (is.null(topindep_var) && is.null(interact_vars)) {
# select best glmnet model upto now
dsp_models_df <- orderBy(model_sel_frmla <- get_model_sel_frmla(),
glb_models_df)
dsp_models_df <- subset(dsp_models_df,
grepl(".glmnet", id, fixed = TRUE))
bst_mdl_id <- dsp_models_df$id[1]
mdl_id_pfx <-
paste(c(head(unlist(strsplit(bst_mdl_id, "[.]")), -1), "Interact"),
collapse=".")
# select important features
if (is.null(bst_featsimp_df <-
myget_feats_importance(glb_models_lst[[bst_mdl_id]]))) {
warning("Base model for RFE.Interact: ", bst_mdl_id,
" has no important features")
next
}
topindep_ix <- 1
while (is.null(topindep_var) && (topindep_ix <= nrow(bst_featsimp_df))) {
topindep_var <- row.names(bst_featsimp_df)[topindep_ix]
if (grepl(".fctr", topindep_var, fixed=TRUE))
topindep_var <-
paste0(unlist(strsplit(topindep_var, ".fctr"))[1], ".fctr")
if (topindep_var %in% names(glbFeatsInteractionOnly)) {
topindep_var <- NULL; topindep_ix <- topindep_ix + 1
} else break
}
# select features with importance > max(10, importance of .rnorm) & is not highest
# combine factor dummy features to just the factor feature
if (length(pos_rnorm <-
grep(".rnorm", row.names(bst_featsimp_df), fixed=TRUE)) > 0)
imp_rnorm <- bst_featsimp_df[pos_rnorm, 1] else
imp_rnorm <- NA
imp_cutoff <- max(10, imp_rnorm, na.rm=TRUE)
interact_vars <-
tail(row.names(subset(bst_featsimp_df,
imp > imp_cutoff)), -1)
if (length(interact_vars) > 0) {
interact_vars <-
myadjust_interaction_feats(myextract_actual_feats(interact_vars))
interact_vars <-
interact_vars[!grepl(topindep_var, interact_vars, fixed=TRUE)]
}
### bid0_sp only
# interact_vars <- c(
# "biddable", "D.ratio.sum.TfIdf.wrds.n", "D.TfIdf.sum.stem.stop.Ratio", "D.sum.TfIdf",
# "D.TfIdf.sum.post.stop", "D.TfIdf.sum.post.stem", "D.ratio.wrds.stop.n.wrds.n", "D.chrs.uppr.n.log",
# "D.chrs.n.log", "color.fctr"
# # , "condition.fctr", "prdl.my.descr.fctr"
# )
# interact_vars <- setdiff(interact_vars, c("startprice.dgt2.is9", "color.fctr"))
###
indep_vars <- myextract_actual_feats(row.names(bst_featsimp_df))
indep_vars <- setdiff(indep_vars, topindep_var)
if (length(interact_vars) > 0) {
indep_vars <-
setdiff(indep_vars, myextract_actual_feats(interact_vars))
indep_vars <- c(indep_vars,
paste(topindep_var, setdiff(interact_vars, topindep_var),
sep = "*"))
} else indep_vars <- union(indep_vars, topindep_var)
}
}
if (is.null(indep_vars))
indep_vars <- glb_mdl_feats_lst[[mdl_id_pfx]]
if (is.null(indep_vars) && grepl("RFE\\.", mdl_id_pfx))
indep_vars <- myextract_actual_feats(predictors(rfe_fit_results))
if (is.null(indep_vars))
indep_vars <- subset(glb_feats_df, !nzv & (exclude.as.feat != 1))[, "id"]
if ((length(indep_vars) == 1) && (grepl("^%<d-%", indep_vars))) {
indep_vars <-
eval(parse(text = str_trim(unlist(strsplit(indep_vars, "%<d-%"))[2])))
}
indep_vars <- myadjust_interaction_feats(indep_vars)
if (grepl("\\.Interact", mdl_id_pfx)) {
# if (method != tail(unlist(strsplit(bst_mdl_id, "[.]")), 1)) next
if (is.null(glbMdlFamilies[[mdl_id_pfx]])) {
if (!is.null(glbMdlFamilies[["Best.Interact"]]))
glbMdlFamilies[[mdl_id_pfx]] <-
glbMdlFamilies[["Best.Interact"]]
}
}
if (!is.null(glbObsFitOutliers[[mdl_id_pfx]])) {
fitobs_df <- glbObsFit[!(glbObsFit[, glbFeatsId] %in%
glbObsFitOutliers[[mdl_id_pfx]]), ]
print(sprintf("Outliers removed: %d", nrow(glbObsFit) - nrow(fitobs_df)))
print(setdiff(glbObsFit[, glbFeatsId], fitobs_df[, glbFeatsId]))
} else fitobs_df <- glbObsFit
if (is.null(glbMdlFamilies[[mdl_id_pfx]]))
mdl_methods <- glbMdlMethods else
mdl_methods <- glbMdlFamilies[[mdl_id_pfx]]
for (method in mdl_methods) {
if (method %in% c("rpart", "rf")) {
# rpart: fubar's the tree
# rf: skip the scenario w/ .rnorm for speed
indep_vars <- setdiff(indep_vars, c(".rnorm"))
#mdl_id <- paste0(mdl_id_pfx, ".no.rnorm")
}
fit.models_1_chunk_df <- myadd_chunk(fit.models_1_chunk_df,
paste0("fit.models_1_", mdl_id_pfx), major.inc = FALSE,
label.minor = method)
ret_lst <-
myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = mdl_id_pfx,
type = glb_model_type,
tune.df = glbMdlTuneParams,
trainControl.method = "repeatedcv", # or "none" if nominalWorkflow is crashing
trainControl.number = glb_rcv_n_folds,
trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
trainControl.allowParallel = glbMdlAllowParallel,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = method)),
indep_vars = indep_vars, rsp_var = glb_rsp_var,
fit_df = fitobs_df, OOB_df = glbObsOOB)
# ntv_mdl <- glmnet(x = as.matrix(
# fitobs_df[, indep_vars]),
# y = as.factor(as.character(
# fitobs_df[, glb_rsp_var])),
# family = "multinomial")
# bgn = 1; end = 100;
# ntv_mdl <- glmnet(x = as.matrix(
# subset(fitobs_df, pop.fctr != "crypto")[bgn:end, indep_vars]),
# y = as.factor(as.character(
# subset(fitobs_df, pop.fctr != "crypto")[bgn:end, glb_rsp_var])),
# family = "multinomial")
}
}
## label step_major step_minor label_minor bgn end
## 1 fit.models_1_bgn 1 0 setup 71.719 71.73
## 2 fit.models_1_All.X 1 1 setup 71.731 NA
## elapsed
## 1 0.011
## 2 NA
## label step_major step_minor label_minor bgn end
## 2 fit.models_1_All.X 1 1 setup 71.731 71.738
## 3 fit.models_1_All.X 1 2 glmnet 71.738 NA
## elapsed
## 2 0.007
## 3 NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: All.X##rcv#glmnet"
## [1] " indep_vars: .pos,.rnorm"
## [1] "myfit_mdl: setup complete: 0.713000 secs"
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 0.325, lambda = 0.00649 on full training set
## [1] "myfit_mdl: train complete: 2.719000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = mdl_id_pfx, : model's bestTune found at an extreme of
## tuneGrid for parameter: lambda
## Length Class Mode
## a0 20 -none- numeric
## beta 40 dgCMatrix S4
## df 20 -none- numeric
## dim 2 -none- numeric
## lambda 20 -none- numeric
## dev.ratio 20 -none- numeric
## nulldev 1 -none- numeric
## npasses 1 -none- numeric
## jerr 1 -none- numeric
## offset 1 -none- logical
## classnames 2 -none- character
## call 5 -none- call
## nobs 1 -none- numeric
## lambdaOpt 1 -none- numeric
## xNames 2 -none- character
## problemType 1 -none- character
## tuneValue 2 data.frame list
## obsLevels 2 -none- character
## [1] "min lambda > lambdaOpt:"
## (Intercept) .pos .rnorm
## -7.747964e-02 8.305337e-05 2.446781e-02
## [1] "max lambda < lambdaOpt:"
## [1] "Feats mismatch between coefs_left & rght:"
## [1] "(Intercept)" ".pos" ".rnorm"
## [1] "myfit_mdl: train diagnostics complete: 3.368000 secs"
## Prediction
## Reference N Y
## N 0 499
## Y 0 502
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.014985e-01 0.000000e+00 4.700593e-01 5.329288e-01 5.014985e-01
## AccuracyPValue McnemarPValue
## 5.126189e-01 4.268523e-110
## Prediction
## Reference N Y
## N 0 498
## Y 0 501
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.015015e-01 0.000000e+00 4.700304e-01 5.329637e-01 5.015015e-01
## AccuracyPValue McnemarPValue
## 5.126315e-01 7.044652e-110
## [1] "myfit_mdl: predict complete: 6.404000 secs"
## id feats max.nTuningRuns min.elapsedtime.everything
## 1 All.X##rcv#glmnet .pos,.rnorm 15 2.002
## min.elapsedtime.final max.AUCpROC.fit max.Sens.fit max.Spec.fit
## 1 0.008 0.5203614 0.4809619 0.559761
## max.AUCROCR.fit opt.prob.threshold.fit max.f.score.fit max.Accuracy.fit
## 1 0.5192057 0.4 0.6679973 0.5008332
## max.AccuracyLower.fit max.AccuracyUpper.fit max.Kappa.fit
## 1 0.4700593 0.5329288 0.001520074
## max.AUCpROC.OOB max.Sens.OOB max.Spec.OOB max.AUCROCR.OOB
## 1 0.5164731 0.502008 0.5309381 0.508453
## opt.prob.threshold.OOB max.f.score.OOB max.Accuracy.OOB
## 1 0.4 0.668 0.5015015
## max.AccuracyLower.OOB max.AccuracyUpper.OOB max.Kappa.OOB
## 1 0.4700304 0.5329637 0
## max.AccuracySD.fit max.KappaSD.fit
## 1 0.02299258 0.04598811
## [1] "myfit_mdl: exit: 6.419000 secs"
## label step_major step_minor label_minor bgn end
## 3 fit.models_1_All.X 1 2 glmnet 71.738 78.163
## 4 fit.models_1_All.X 1 3 glm 78.164 NA
## elapsed
## 3 6.425
## 4 NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: All.X##rcv#glm"
## [1] " indep_vars: .pos,.rnorm"
## [1] "myfit_mdl: setup complete: 0.720000 secs"
## Aggregating results
## Fitting final model on full training set
## [1] "myfit_mdl: train complete: 1.916000 secs"
##
## Call:
## NULL
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.257 -1.180 1.100 1.173 1.238
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.0963689 0.1277389 -0.754 0.451
## .pos 0.0001019 0.0001097 0.929 0.353
## .rnorm 0.0346965 0.0623669 0.556 0.578
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1387.7 on 1000 degrees of freedom
## Residual deviance: 1386.5 on 998 degrees of freedom
## AIC: 1392.5
##
## Number of Fisher Scoring iterations: 3
##
## [1] "myfit_mdl: train diagnostics complete: 2.741000 secs"
## Prediction
## Reference N Y
## N 0 499
## Y 0 502
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.014985e-01 0.000000e+00 4.700593e-01 5.329288e-01 5.014985e-01
## AccuracyPValue McnemarPValue
## 5.126189e-01 4.268523e-110
## Prediction
## Reference N Y
## N 0 498
## Y 0 501
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.015015e-01 0.000000e+00 4.700304e-01 5.329637e-01 5.015015e-01
## AccuracyPValue McnemarPValue
## 5.126315e-01 7.044652e-110
## [1] "myfit_mdl: predict complete: 5.736000 secs"
## id feats max.nTuningRuns min.elapsedtime.everything
## 1 All.X##rcv#glm .pos,.rnorm 1 1.19
## min.elapsedtime.final max.AUCpROC.fit max.Sens.fit max.Spec.fit
## 1 0.012 0.5163654 0.4769539 0.5557769
## max.AUCROCR.fit opt.prob.threshold.fit max.f.score.fit max.Accuracy.fit
## 1 0.5194293 0.4 0.6679973 0.5058242
## max.AccuracyLower.fit max.AccuracyUpper.fit max.Kappa.fit
## 1 0.4700593 0.5329288 0.01151507
## max.AUCpROC.OOB max.Sens.OOB max.Spec.OOB max.AUCROCR.OOB
## 1 0.5144951 0.5080321 0.5209581 0.5071664
## opt.prob.threshold.OOB max.f.score.OOB max.Accuracy.OOB
## 1 0.4 0.668 0.5015015
## max.AccuracyLower.OOB max.AccuracyUpper.OOB max.Kappa.OOB
## 1 0.4700304 0.5329637 0
## max.AccuracySD.fit max.KappaSD.fit
## 1 0.02725681 0.0545643
## [1] "myfit_mdl: exit: 5.751000 secs"
# Check if other preProcess methods improve model performance
fit.models_1_chunk_df <-
myadd_chunk(fit.models_1_chunk_df, "fit.models_1_preProc", major.inc = FALSE,
label.minor = "preProc")
## label step_major step_minor label_minor bgn end
## 4 fit.models_1_All.X 1 3 glm 78.164 83.956
## 5 fit.models_1_preProc 1 4 preProc 83.957 NA
## elapsed
## 4 5.792
## 5 NA
mdl_id <- orderBy(get_model_sel_frmla(), glb_models_df)[1, "id"]
indep_vars_vctr <- trim(unlist(strsplit(glb_models_df[glb_models_df$id == mdl_id,
"feats"], "[,]")))
method <- tail(unlist(strsplit(mdl_id, "[.]")), 1)
mdl_id_pfx <- paste0(head(unlist(strsplit(mdl_id, "[.]")), -1), collapse = ".")
if (!is.null(glbObsFitOutliers[[mdl_id_pfx]])) {
fitobs_df <- glbObsFit[!(glbObsFit[, glbFeatsId] %in%
glbObsFitOutliers[[mdl_id_pfx]]), ]
print(sprintf("Outliers removed: %d", nrow(glbObsFit) - nrow(fitobs_df)))
print(setdiff(glbObsFit[, glbFeatsId], fitobs_df[, glbFeatsId]))
} else fitobs_df <- glbObsFit
for (prePr in glb_preproc_methods) {
# The operations are applied in this order:
# Box-Cox/Yeo-Johnson transformation, centering, scaling, range, imputation, PCA, ICA then spatial sign.
ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
id.prefix=mdl_id_pfx,
type=glb_model_type, tune.df=glbMdlTuneParams,
trainControl.method="repeatedcv",
trainControl.number=glb_rcv_n_folds,
trainControl.repeats=glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method=method, train.preProcess=prePr)),
indep_vars=indep_vars_vctr, rsp_var=glb_rsp_var,
fit_df=fitobs_df, OOB_df=glbObsOOB)
}
# If (All|RFE).X.glm is less accurate than Low.Cor.X.glm
# check NA coefficients & filter appropriate terms in indep_vars_vctr
# if (method == "glm") {
# orig_glm <- glb_models_lst[[paste0(mdl_id, ".", model_method)]]$finalModel
# orig_glm <- glb_models_lst[["All.X.glm"]]$finalModel; print(summary(orig_glm))
# orig_glm <- glb_models_lst[["RFE.X.glm"]]$finalModel; print(summary(orig_glm))
# require(car)
# vif_orig_glm <- vif(orig_glm); print(vif_orig_glm)
# # if vif errors out with "there are aliased coefficients in the model"
# alias_orig_glm <- alias(orig_glm); alias_complete_orig_glm <- (alias_orig_glm$Complete > 0); alias_complete_orig_glm <- alias_complete_orig_glm[rowSums(alias_complete_orig_glm) > 0, colSums(alias_complete_orig_glm) > 0]; print(alias_complete_orig_glm)
# print(vif_orig_glm[!is.na(vif_orig_glm) & (vif_orig_glm == Inf)])
# print(which.max(vif_orig_glm))
# print(sort(vif_orig_glm[vif_orig_glm >= 1.0e+03], decreasing=TRUE))
# glbObsFit[c(1143, 3637, 3953, 4105), c("UniqueID", "Popular", "H.P.quandary", "Headline")]
# glb_feats_df[glb_feats_df$id %in% grep("[HSA]\\.chrs.n.log", glb_feats_df$id, value=TRUE) | glb_feats_df$cor.high.X %in% grep("[HSA]\\.chrs.n.log", glb_feats_df$id, value=TRUE), ]
# all.equal(glbObsAll$S.chrs.uppr.n.log, glbObsAll$A.chrs.uppr.n.log)
# cor(glbObsAll$S.T.herald, glbObsAll$S.T.tribun)
# mydspObs(Abstract.contains="[Dd]iar", cols=("Abstract"), all=TRUE)
# subset(glb_feats_df, cor.y.abs <= glb_feats_df[glb_feats_df$id == ".rnorm", "cor.y.abs"])
# corxx_mtrx <- cor(data.matrix(glbObsAll[, setdiff(names(glbObsAll), myfind_chr_cols_df(glbObsAll))]), use="pairwise.complete.obs"); abs_corxx_mtrx <- abs(corxx_mtrx); diag(abs_corxx_mtrx) <- 0
# which.max(abs_corxx_mtrx["S.T.tribun", ])
# abs_corxx_mtrx["A.npnct08.log", "S.npnct08.log"]
# step_glm <- step(orig_glm)
# }
# Since caret does not optimize rpart well
# if (method == "rpart")
# ret_lst <- myfit_mdl(mdl_id=paste0(mdl_id_pfx, ".cp.0"), model_method=method,
# indep_vars_vctr=indep_vars_vctr,
# model_type=glb_model_type,
# rsp_var=glb_rsp_var,
# fit_df=glbObsFit, OOB_df=glbObsOOB,
# n_cv_folds=0, tune_models_df=data.frame(parameter="cp", min=0.0, max=0.0, by=0.1))
# User specified
# Ensure at least 2 vars in each regression; else varImp crashes
# sav_models_lst <- glb_models_lst; sav_models_df <- glb_models_df; sav_featsimp_df <- glb_featsimp_df; all.equal(sav_featsimp_df, glb_featsimp_df)
# glb_models_lst <- sav_models_lst; glb_models_df <- sav_models_df; glm_featsimp_df <- sav_featsimp_df
# easier to exclude features
# require(gdata) # needed for trim
# mdl_id <- "";
# indep_vars_vctr <- head(subset(glb_models_df, grepl("All\\.X\\.", mdl_id), select=feats)
# , 1)[, "feats"]
# indep_vars_vctr <- trim(unlist(strsplit(indep_vars_vctr, "[,]")))
# indep_vars_vctr <- setdiff(indep_vars_vctr, ".rnorm")
# easier to include features
#stop(here"); sav_models_df <- glb_models_df; glb_models_df <- sav_models_df
# !_sp
# mdl_id <- "csm"; indep_vars_vctr <- c(NULL
# ,"prdline.my.fctr", "prdline.my.fctr:.clusterid.fctr"
# ,"prdline.my.fctr*biddable"
# #,"prdline.my.fctr*startprice.log"
# #,"prdline.my.fctr*startprice.diff"
# ,"prdline.my.fctr*condition.fctr"
# ,"prdline.my.fctr*D.terms.post.stop.n"
# #,"prdline.my.fctr*D.terms.post.stem.n"
# ,"prdline.my.fctr*cellular.fctr"
# # ,"<feat1>:<feat2>"
# )
# for (method in glbMdlMethods) {
# ret_lst <- myfit_mdl(mdl_id=mdl_id, model_method=method,
# indep_vars_vctr=indep_vars_vctr,
# model_type=glb_model_type,
# rsp_var=glb_rsp_var,
# fit_df=glbObsFit, OOB_df=glbObsOOB,
# n_cv_folds=glb_rcv_n_folds, tune_models_df=glbMdlTuneParams)
# csm_mdl_id <- paste0(mdl_id, ".", method)
# csm_featsimp_df <- myget_feats_importance(glb_models_lst[[paste0(mdl_id, ".",
# method)]]); print(head(csm_featsimp_df))
# }
###
# Ntv.1.lm <- lm(reformulate(indep_vars_vctr, glb_rsp_var), glbObsTrn); print(summary(Ntv.1.lm))
#glb_models_df[, "max.Accuracy.OOB", FALSE]
#varImp(glb_models_lst[["Low.cor.X.glm"]])
#orderBy(~ -Overall, varImp(glb_models_lst[["All.X.2.glm"]])$imp)
#orderBy(~ -Overall, varImp(glb_models_lst[["All.X.3.glm"]])$imp)
#glb_feats_df[grepl("npnct28", glb_feats_df$id), ]
# User specified bivariate models
# indep_vars_vctr_lst <- list()
# for (feat in setdiff(names(glbObsFit),
# union(glb_rsp_var, glbFeatsExclude)))
# indep_vars_vctr_lst[["feat"]] <- feat
# User specified combinatorial models
# indep_vars_vctr_lst <- list()
# combn_mtrx <- combn(c("<feat1_name>", "<feat2_name>", "<featn_name>"),
# <num_feats_to_choose>)
# for (combn_ix in 1:ncol(combn_mtrx))
# #print(combn_mtrx[, combn_ix])
# indep_vars_vctr_lst[[combn_ix]] <- combn_mtrx[, combn_ix]
# template for myfit_mdl
# rf is hard-coded in caret to recognize only Accuracy / Kappa evaluation metrics
# only for OOB in trainControl ?
# ret_lst <- myfit_mdl_fn(mdl_id=paste0(mdl_id_pfx, ""), model_method=method,
# indep_vars_vctr=indep_vars_vctr,
# rsp_var=glb_rsp_var,
# fit_df=glbObsFit, OOB_df=glbObsOOB,
# n_cv_folds=glb_rcv_n_folds, tune_models_df=glbMdlTuneParams,
# model_loss_mtrx=glbMdlMetric_terms,
# model_summaryFunction=glbMdlMetricSummaryFn,
# model_metric=glbMdlMetricSummary,
# model_metric_maximize=glbMdlMetricMaximize)
# Simplify a model
# fit_df <- glbObsFit; glb_mdl <- step(<complex>_mdl)
# Non-caret models
# rpart_area_mdl <- rpart(reformulate("Area", response=glb_rsp_var),
# data=glbObsFit, #method="class",
# control=rpart.control(cp=0.12),
# parms=list(loss=glbMdlMetric_terms))
# print("rpart_sel_wlm_mdl"); prp(rpart_sel_wlm_mdl)
#
print(glb_models_df)
## id feats
## MFO###myMFO_classfr MFO###myMFO_classfr .rnorm
## Random###myrandom_classfr Random###myrandom_classfr .rnorm
## Max.cor.Y.rcv.1X1###glmnet Max.cor.Y.rcv.1X1###glmnet .pos,.rnorm
## Max.cor.Y##rcv#rpart Max.cor.Y##rcv#rpart .pos,.rnorm
## Low.cor.X##rcv#glmnet Low.cor.X##rcv#glmnet .pos,.rnorm
## All.X##rcv#glmnet All.X##rcv#glmnet .pos,.rnorm
## All.X##rcv#glm All.X##rcv#glm .pos,.rnorm
## max.nTuningRuns min.elapsedtime.everything
## MFO###myMFO_classfr 0 0.397
## Random###myrandom_classfr 0 0.260
## Max.cor.Y.rcv.1X1###glmnet 0 0.707
## Max.cor.Y##rcv#rpart 5 1.663
## Low.cor.X##rcv#glmnet 15 1.913
## All.X##rcv#glmnet 15 2.002
## All.X##rcv#glm 1 1.190
## min.elapsedtime.final max.AUCpROC.fit
## MFO###myMFO_classfr 0.004 0.5000000
## Random###myrandom_classfr 0.001 0.4945369
## Max.cor.Y.rcv.1X1###glmnet 0.013 0.5193475
## Max.cor.Y##rcv#rpart 0.016 0.6282845
## Low.cor.X##rcv#glmnet 0.008 0.5203614
## All.X##rcv#glmnet 0.008 0.5203614
## All.X##rcv#glm 0.012 0.5163654
## max.Sens.fit max.Spec.fit max.AUCROCR.fit
## MFO###myMFO_classfr 0.0000000 1.0000000 0.5000000
## Random###myrandom_classfr 0.5050100 0.4840637 0.4764948
## Max.cor.Y.rcv.1X1###glmnet 0.4749499 0.5637450 0.5191738
## Max.cor.Y##rcv#rpart 0.5991984 0.6573705 0.6561609
## Low.cor.X##rcv#glmnet 0.4809619 0.5597610 0.5192057
## All.X##rcv#glmnet 0.4809619 0.5597610 0.5192057
## All.X##rcv#glm 0.4769539 0.5557769 0.5194293
## opt.prob.threshold.fit max.f.score.fit
## MFO###myMFO_classfr 0.4 0.6679973
## Random###myrandom_classfr 0.4 0.6679973
## Max.cor.Y.rcv.1X1###glmnet 0.4 0.6679973
## Max.cor.Y##rcv#rpart 0.3 0.6831683
## Low.cor.X##rcv#glmnet 0.4 0.6679973
## All.X##rcv#glmnet 0.4 0.6679973
## All.X##rcv#glm 0.4 0.6679973
## max.Accuracy.fit max.AccuracyLower.fit
## MFO###myMFO_classfr 0.5014985 0.4700593
## Random###myrandom_classfr 0.5014985 0.4700593
## Max.cor.Y.rcv.1X1###glmnet 0.5014985 0.4700593
## Max.cor.Y##rcv#rpart 0.5098352 0.5210284
## Low.cor.X##rcv#glmnet 0.5008332 0.4700593
## All.X##rcv#glmnet 0.5008332 0.4700593
## All.X##rcv#glm 0.5058242 0.4700593
## max.AccuracyUpper.fit max.Kappa.fit
## MFO###myMFO_classfr 0.5329288 0.000000000
## Random###myrandom_classfr 0.5329288 0.000000000
## Max.cor.Y.rcv.1X1###glmnet 0.5329288 0.000000000
## Max.cor.Y##rcv#rpart 0.5835573 0.019616754
## Low.cor.X##rcv#glmnet 0.5329288 0.001520074
## All.X##rcv#glmnet 0.5329288 0.001520074
## All.X##rcv#glm 0.5329288 0.011515069
## max.AUCpROC.OOB max.Sens.OOB max.Spec.OOB
## MFO###myMFO_classfr 0.5000000 0.0000000 1.0000000
## Random###myrandom_classfr 0.5054710 0.4939759 0.5169661
## Max.cor.Y.rcv.1X1###glmnet 0.5174771 0.5040161 0.5309381
## Max.cor.Y##rcv#rpart 0.5005952 0.5321285 0.4690619
## Low.cor.X##rcv#glmnet 0.5164731 0.5020080 0.5309381
## All.X##rcv#glmnet 0.5164731 0.5020080 0.5309381
## All.X##rcv#glm 0.5144951 0.5080321 0.5209581
## max.AUCROCR.OOB opt.prob.threshold.OOB
## MFO###myMFO_classfr 0.5000000 0.4
## Random###myrandom_classfr 0.4974749 0.4
## Max.cor.Y.rcv.1X1###glmnet 0.5082125 0.4
## Max.cor.Y##rcv#rpart 0.4868235 0.0
## Low.cor.X##rcv#glmnet 0.5084530 0.4
## All.X##rcv#glmnet 0.5084530 0.4
## All.X##rcv#glm 0.5071664 0.4
## max.f.score.OOB max.Accuracy.OOB
## MFO###myMFO_classfr 0.668 0.5015015
## Random###myrandom_classfr 0.668 0.5015015
## Max.cor.Y.rcv.1X1###glmnet 0.668 0.5015015
## Max.cor.Y##rcv#rpart 0.668 0.5015015
## Low.cor.X##rcv#glmnet 0.668 0.5015015
## All.X##rcv#glmnet 0.668 0.5015015
## All.X##rcv#glm 0.668 0.5015015
## max.AccuracyLower.OOB max.AccuracyUpper.OOB
## MFO###myMFO_classfr 0.4700304 0.5329637
## Random###myrandom_classfr 0.4700304 0.5329637
## Max.cor.Y.rcv.1X1###glmnet 0.4700304 0.5329637
## Max.cor.Y##rcv#rpart 0.4700304 0.5329637
## Low.cor.X##rcv#glmnet 0.4700304 0.5329637
## All.X##rcv#glmnet 0.4700304 0.5329637
## All.X##rcv#glm 0.4700304 0.5329637
## max.Kappa.OOB max.AccuracySD.fit
## MFO###myMFO_classfr 0 NA
## Random###myrandom_classfr 0 NA
## Max.cor.Y.rcv.1X1###glmnet 0 NA
## Max.cor.Y##rcv#rpart 0 0.02434529
## Low.cor.X##rcv#glmnet 0 0.02299258
## All.X##rcv#glmnet 0 0.02299258
## All.X##rcv#glm 0 0.02725681
## max.KappaSD.fit
## MFO###myMFO_classfr NA
## Random###myrandom_classfr NA
## Max.cor.Y.rcv.1X1###glmnet NA
## Max.cor.Y##rcv#rpart 0.04858550
## Low.cor.X##rcv#glmnet 0.04598811
## All.X##rcv#glmnet 0.04598811
## All.X##rcv#glm 0.05456430
rm(ret_lst)
fit.models_1_chunk_df <-
myadd_chunk(fit.models_1_chunk_df, "fit.models_1_end", major.inc = FALSE,
label.minor = "teardown")
## label step_major step_minor label_minor bgn end
## 5 fit.models_1_preProc 1 4 preProc 83.957 84.039
## 6 fit.models_1_end 1 5 teardown 84.040 NA
## elapsed
## 5 0.082
## 6 NA
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc = FALSE)
## label step_major step_minor label_minor bgn end elapsed
## 17 fit.models 8 1 1 68.231 84.049 15.818
## 18 fit.models 8 2 2 84.050 NA NA
fit.models_2_chunk_df <-
myadd_chunk(NULL, "fit.models_2_bgn", label.minor = "setup")
## label step_major step_minor label_minor bgn end elapsed
## 1 fit.models_2_bgn 1 0 setup 87.562 NA NA
plt_models_df <- glb_models_df[, -grep("SD|Upper|Lower", names(glb_models_df))]
for (var in grep("^min.", names(plt_models_df), value=TRUE)) {
plt_models_df[, sub("min.", "inv.", var)] <-
#ifelse(all(is.na(tmp <- plt_models_df[, var])), NA, 1.0 / tmp)
1.0 / plt_models_df[, var]
plt_models_df <- plt_models_df[ , -grep(var, names(plt_models_df))]
}
print(plt_models_df)
## id feats
## MFO###myMFO_classfr MFO###myMFO_classfr .rnorm
## Random###myrandom_classfr Random###myrandom_classfr .rnorm
## Max.cor.Y.rcv.1X1###glmnet Max.cor.Y.rcv.1X1###glmnet .pos,.rnorm
## Max.cor.Y##rcv#rpart Max.cor.Y##rcv#rpart .pos,.rnorm
## Low.cor.X##rcv#glmnet Low.cor.X##rcv#glmnet .pos,.rnorm
## All.X##rcv#glmnet All.X##rcv#glmnet .pos,.rnorm
## All.X##rcv#glm All.X##rcv#glm .pos,.rnorm
## max.nTuningRuns max.AUCpROC.fit max.Sens.fit
## MFO###myMFO_classfr 0 0.5000000 0.0000000
## Random###myrandom_classfr 0 0.4945369 0.5050100
## Max.cor.Y.rcv.1X1###glmnet 0 0.5193475 0.4749499
## Max.cor.Y##rcv#rpart 5 0.6282845 0.5991984
## Low.cor.X##rcv#glmnet 15 0.5203614 0.4809619
## All.X##rcv#glmnet 15 0.5203614 0.4809619
## All.X##rcv#glm 1 0.5163654 0.4769539
## max.Spec.fit max.AUCROCR.fit
## MFO###myMFO_classfr 1.0000000 0.5000000
## Random###myrandom_classfr 0.4840637 0.4764948
## Max.cor.Y.rcv.1X1###glmnet 0.5637450 0.5191738
## Max.cor.Y##rcv#rpart 0.6573705 0.6561609
## Low.cor.X##rcv#glmnet 0.5597610 0.5192057
## All.X##rcv#glmnet 0.5597610 0.5192057
## All.X##rcv#glm 0.5557769 0.5194293
## opt.prob.threshold.fit max.f.score.fit
## MFO###myMFO_classfr 0.4 0.6679973
## Random###myrandom_classfr 0.4 0.6679973
## Max.cor.Y.rcv.1X1###glmnet 0.4 0.6679973
## Max.cor.Y##rcv#rpart 0.3 0.6831683
## Low.cor.X##rcv#glmnet 0.4 0.6679973
## All.X##rcv#glmnet 0.4 0.6679973
## All.X##rcv#glm 0.4 0.6679973
## max.Accuracy.fit max.Kappa.fit max.AUCpROC.OOB
## MFO###myMFO_classfr 0.5014985 0.000000000 0.5000000
## Random###myrandom_classfr 0.5014985 0.000000000 0.5054710
## Max.cor.Y.rcv.1X1###glmnet 0.5014985 0.000000000 0.5174771
## Max.cor.Y##rcv#rpart 0.5098352 0.019616754 0.5005952
## Low.cor.X##rcv#glmnet 0.5008332 0.001520074 0.5164731
## All.X##rcv#glmnet 0.5008332 0.001520074 0.5164731
## All.X##rcv#glm 0.5058242 0.011515069 0.5144951
## max.Sens.OOB max.Spec.OOB max.AUCROCR.OOB
## MFO###myMFO_classfr 0.0000000 1.0000000 0.5000000
## Random###myrandom_classfr 0.4939759 0.5169661 0.4974749
## Max.cor.Y.rcv.1X1###glmnet 0.5040161 0.5309381 0.5082125
## Max.cor.Y##rcv#rpart 0.5321285 0.4690619 0.4868235
## Low.cor.X##rcv#glmnet 0.5020080 0.5309381 0.5084530
## All.X##rcv#glmnet 0.5020080 0.5309381 0.5084530
## All.X##rcv#glm 0.5080321 0.5209581 0.5071664
## opt.prob.threshold.OOB max.f.score.OOB
## MFO###myMFO_classfr 0.4 0.668
## Random###myrandom_classfr 0.4 0.668
## Max.cor.Y.rcv.1X1###glmnet 0.4 0.668
## Max.cor.Y##rcv#rpart 0.0 0.668
## Low.cor.X##rcv#glmnet 0.4 0.668
## All.X##rcv#glmnet 0.4 0.668
## All.X##rcv#glm 0.4 0.668
## max.Accuracy.OOB max.Kappa.OOB
## MFO###myMFO_classfr 0.5015015 0
## Random###myrandom_classfr 0.5015015 0
## Max.cor.Y.rcv.1X1###glmnet 0.5015015 0
## Max.cor.Y##rcv#rpart 0.5015015 0
## Low.cor.X##rcv#glmnet 0.5015015 0
## All.X##rcv#glmnet 0.5015015 0
## All.X##rcv#glm 0.5015015 0
## inv.elapsedtime.everything
## MFO###myMFO_classfr 2.5188917
## Random###myrandom_classfr 3.8461538
## Max.cor.Y.rcv.1X1###glmnet 1.4144272
## Max.cor.Y##rcv#rpart 0.6013229
## Low.cor.X##rcv#glmnet 0.5227392
## All.X##rcv#glmnet 0.4995005
## All.X##rcv#glm 0.8403361
## inv.elapsedtime.final
## MFO###myMFO_classfr 250.00000
## Random###myrandom_classfr 1000.00000
## Max.cor.Y.rcv.1X1###glmnet 76.92308
## Max.cor.Y##rcv#rpart 62.50000
## Low.cor.X##rcv#glmnet 125.00000
## All.X##rcv#glmnet 125.00000
## All.X##rcv#glm 83.33333
# print(myplot_radar(radar_inp_df=plt_models_df))
# print(myplot_radar(radar_inp_df=subset(plt_models_df,
# !(mdl_id %in% grep("random|MFO", plt_models_df$id, value=TRUE)))))
# Compute CI for <metric>SD
glb_models_df <- mutate(glb_models_df,
max.df = ifelse(max.nTuningRuns > 1, max.nTuningRuns - 1, NA),
min.sd2ci.scaler = ifelse(is.na(max.df), NA, qt(0.975, max.df)))
for (var in grep("SD", names(glb_models_df), value=TRUE)) {
# Does CI alredy exist ?
var_components <- unlist(strsplit(var, "SD"))
varActul <- paste0(var_components[1], var_components[2])
varUpper <- paste0(var_components[1], "Upper", var_components[2])
varLower <- paste0(var_components[1], "Lower", var_components[2])
if (varUpper %in% names(glb_models_df)) {
warning(varUpper, " already exists in glb_models_df")
# Assuming Lower also exists
next
}
print(sprintf("var:%s", var))
# CI is dependent on sample size in t distribution; df=n-1
glb_models_df[, varUpper] <- glb_models_df[, varActul] +
glb_models_df[, "min.sd2ci.scaler"] * glb_models_df[, var]
glb_models_df[, varLower] <- glb_models_df[, varActul] -
glb_models_df[, "min.sd2ci.scaler"] * glb_models_df[, var]
}
## Warning: max.AccuracyUpper.fit already exists in glb_models_df
## [1] "var:max.KappaSD.fit"
# Plot metrics with CI
plt_models_df <- glb_models_df[, "id", FALSE]
pltCI_models_df <- glb_models_df[, "id", FALSE]
for (var in grep("Upper", names(glb_models_df), value=TRUE)) {
var_components <- unlist(strsplit(var, "Upper"))
col_name <- unlist(paste(var_components, collapse=""))
plt_models_df[, col_name] <- glb_models_df[, col_name]
for (name in paste0(var_components[1], c("Upper", "Lower"), var_components[2]))
pltCI_models_df[, name] <- glb_models_df[, name]
}
build_statsCI_data <- function(plt_models_df) {
mltd_models_df <- melt(plt_models_df, id.vars="id")
mltd_models_df$data <- sapply(1:nrow(mltd_models_df),
function(row_ix) tail(unlist(strsplit(as.character(
mltd_models_df[row_ix, "variable"]), "[.]")), 1))
mltd_models_df$label <- sapply(1:nrow(mltd_models_df),
function(row_ix) head(unlist(strsplit(as.character(
mltd_models_df[row_ix, "variable"]),
paste0(".", mltd_models_df[row_ix, "data"]))), 1))
#print(mltd_models_df)
return(mltd_models_df)
}
mltd_models_df <- build_statsCI_data(plt_models_df)
mltdCI_models_df <- melt(pltCI_models_df, id.vars="id")
for (row_ix in 1:nrow(mltdCI_models_df)) {
for (type in c("Upper", "Lower")) {
if (length(var_components <- unlist(strsplit(
as.character(mltdCI_models_df[row_ix, "variable"]), type))) > 1) {
#print(sprintf("row_ix:%d; type:%s; ", row_ix, type))
mltdCI_models_df[row_ix, "label"] <- var_components[1]
mltdCI_models_df[row_ix, "data"] <-
unlist(strsplit(var_components[2], "[.]"))[2]
mltdCI_models_df[row_ix, "type"] <- type
break
}
}
}
wideCI_models_df <- reshape(subset(mltdCI_models_df, select=-variable),
timevar="type",
idvar=setdiff(names(mltdCI_models_df), c("type", "value", "variable")),
direction="wide")
#print(wideCI_models_df)
mrgdCI_models_df <- merge(wideCI_models_df, mltd_models_df, all.x=TRUE)
#print(mrgdCI_models_df)
# Merge stats back in if CIs don't exist
goback_vars <- c()
for (var in unique(mltd_models_df$label)) {
for (type in unique(mltd_models_df$data)) {
var_type <- paste0(var, ".", type)
# if this data is already present, next
if (var_type %in% unique(paste(mltd_models_df$label, mltd_models_df$data,
sep=".")))
next
#print(sprintf("var_type:%s", var_type))
goback_vars <- c(goback_vars, var_type)
}
}
if (length(goback_vars) > 0) {
mltd_goback_df <- build_statsCI_data(glb_models_df[, c("id", goback_vars)])
mltd_models_df <- rbind(mltd_models_df, mltd_goback_df)
}
# mltd_models_df <- merge(mltd_models_df, glb_models_df[, c("id", "model_method")],
# all.x=TRUE)
png(paste0(glbOut$pfx, "models_bar.png"), width=480*3, height=480*2)
#print(gp <- myplot_bar(mltd_models_df, "id", "value", colorcol_name="model_method") +
print(gp <- myplot_bar(df=mltd_models_df, xcol_name="id", ycol_names="value") +
geom_errorbar(data=mrgdCI_models_df,
mapping=aes(x=mdl_id, ymax=value.Upper, ymin=value.Lower), width=0.5) +
facet_grid(label ~ data, scales="free") +
theme(axis.text.x = element_text(angle = 90,vjust = 0.5)))
## Warning: Removed 4 rows containing missing values (geom_errorbar).
dev.off()
## quartz_off_screen
## 2
print(gp)
## Warning: Removed 4 rows containing missing values (geom_errorbar).
dsp_models_cols <- c("id",
glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE))
# if (glb_is_classification && glb_is_binomial)
# dsp_models_cols <- c(dsp_models_cols, "opt.prob.threshold.OOB")
print(dsp_models_df <- orderBy(get_model_sel_frmla(), glb_models_df)[, dsp_models_cols])
## id max.Accuracy.OOB max.AUCROCR.OOB
## 5 Low.cor.X##rcv#glmnet 0.5015015 0.5084530
## 6 All.X##rcv#glmnet 0.5015015 0.5084530
## 3 Max.cor.Y.rcv.1X1###glmnet 0.5015015 0.5082125
## 7 All.X##rcv#glm 0.5015015 0.5071664
## 1 MFO###myMFO_classfr 0.5015015 0.5000000
## 2 Random###myrandom_classfr 0.5015015 0.4974749
## 4 Max.cor.Y##rcv#rpart 0.5015015 0.4868235
## max.AUCpROC.OOB max.Accuracy.fit opt.prob.threshold.fit
## 5 0.5164731 0.5008332 0.4
## 6 0.5164731 0.5008332 0.4
## 3 0.5174771 0.5014985 0.4
## 7 0.5144951 0.5058242 0.4
## 1 0.5000000 0.5014985 0.4
## 2 0.5054710 0.5014985 0.4
## 4 0.5005952 0.5098352 0.3
## opt.prob.threshold.OOB
## 5 0.4
## 6 0.4
## 3 0.4
## 7 0.4
## 1 0.4
## 2 0.4
## 4 0.0
# print(myplot_radar(radar_inp_df = dsp_models_df))
print("Metrics used for model selection:"); print(get_model_sel_frmla())
## [1] "Metrics used for model selection:"
## ~-max.Accuracy.OOB - max.AUCROCR.OOB - max.AUCpROC.OOB - max.Accuracy.fit -
## opt.prob.threshold.OOB
## <environment: 0x7fbc208158e8>
print(sprintf("Best model id: %s", dsp_models_df[1, "id"]))
## [1] "Best model id: Low.cor.X##rcv#glmnet"
glb_get_predictions <- function(df, mdl_id, rsp_var, prob_threshold_def=NULL, verbose=FALSE) {
mdl <- glb_models_lst[[mdl_id]]
clmnNames <- mygetPredictIds(rsp_var, mdl_id)
predct_var_name <- clmnNames$value
predct_prob_var_name <- clmnNames$prob
predct_accurate_var_name <- clmnNames$is.acc
predct_error_var_name <- clmnNames$err
predct_erabs_var_name <- clmnNames$err.abs
if (glb_is_regression) {
df[, predct_var_name] <- predict(mdl, newdata=df, type="raw")
if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_var_name) +
facet_wrap(reformulate(glbFeatsCategory), scales = "free") +
stat_smooth(method="glm"))
df[, predct_error_var_name] <- df[, predct_var_name] - df[, glb_rsp_var]
if (verbose) print(myplot_scatter(df, predct_var_name, predct_error_var_name) +
#facet_wrap(reformulate(glbFeatsCategory), scales = "free") +
stat_smooth(method="auto"))
if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_error_var_name) +
#facet_wrap(reformulate(glbFeatsCategory), scales = "free") +
stat_smooth(method="glm"))
df[, predct_erabs_var_name] <- abs(df[, predct_error_var_name])
if (verbose) print(head(orderBy(reformulate(c("-", predct_erabs_var_name)), df)))
df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])
}
if (glb_is_classification && glb_is_binomial) {
prob_threshold <- glb_models_df[glb_models_df$id == mdl_id,
"opt.prob.threshold.OOB"]
if (is.null(prob_threshold) || is.na(prob_threshold)) {
warning("Using default probability threshold: ", prob_threshold_def)
if (is.null(prob_threshold <- prob_threshold_def))
stop("Default probability threshold is NULL")
}
df[, predct_prob_var_name] <- predict(mdl, newdata = df, type = "prob")[, 2]
df[, predct_var_name] <-
factor(levels(df[, glb_rsp_var])[
(df[, predct_prob_var_name] >=
prob_threshold) * 1 + 1], levels(df[, glb_rsp_var]))
# if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_var_name) +
# facet_wrap(reformulate(glbFeatsCategory), scales = "free") +
# stat_smooth(method="glm"))
df[, predct_error_var_name] <- df[, predct_var_name] != df[, glb_rsp_var]
# if (verbose) print(myplot_scatter(df, predct_var_name, predct_error_var_name) +
# #facet_wrap(reformulate(glbFeatsCategory), scales = "free") +
# stat_smooth(method="auto"))
# if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_error_var_name) +
# #facet_wrap(reformulate(glbFeatsCategory), scales = "free") +
# stat_smooth(method="glm"))
# if prediction is a TP (true +ve), measure distance from 1.0
tp <- which((df[, predct_var_name] == df[, glb_rsp_var]) &
(df[, predct_var_name] == levels(df[, glb_rsp_var])[2]))
df[tp, predct_erabs_var_name] <- abs(1 - df[tp, predct_prob_var_name])
#rowIx <- which.max(df[tp, predct_erabs_var_name]); df[tp, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
# if prediction is a TN (true -ve), measure distance from 0.0
tn <- which((df[, predct_var_name] == df[, glb_rsp_var]) &
(df[, predct_var_name] == levels(df[, glb_rsp_var])[1]))
df[tn, predct_erabs_var_name] <- abs(0 - df[tn, predct_prob_var_name])
#rowIx <- which.max(df[tn, predct_erabs_var_name]); df[tn, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
# if prediction is a FP (flse +ve), measure distance from 0.0
fp <- which((df[, predct_var_name] != df[, glb_rsp_var]) &
(df[, predct_var_name] == levels(df[, glb_rsp_var])[2]))
df[fp, predct_erabs_var_name] <- abs(0 - df[fp, predct_prob_var_name])
#rowIx <- which.max(df[fp, predct_erabs_var_name]); df[fp, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
# if prediction is a FN (flse -ve), measure distance from 1.0
fn <- which((df[, predct_var_name] != df[, glb_rsp_var]) &
(df[, predct_var_name] == levels(df[, glb_rsp_var])[1]))
df[fn, predct_erabs_var_name] <- abs(1 - df[fn, predct_prob_var_name])
#rowIx <- which.max(df[fn, predct_erabs_var_name]); df[fn, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
if (verbose) print(head(orderBy(reformulate(c("-", predct_erabs_var_name)), df)))
df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])
}
if (glb_is_classification && !glb_is_binomial) {
df[, predct_var_name] <- predict(mdl, newdata = df, type = "raw")
probCls <- predict(mdl, newdata = df, type = "prob")
df[, predct_prob_var_name] <- NA
for (cls in names(probCls)) {
mask <- (df[, predct_var_name] == cls)
df[mask, predct_prob_var_name] <- probCls[mask, cls]
}
if (verbose) print(myplot_histogram(df, predct_prob_var_name,
fill_col_name = predct_var_name))
if (verbose) print(myplot_histogram(df, predct_prob_var_name,
facet_frmla = paste0("~", glb_rsp_var)))
df[, predct_error_var_name] <- df[, predct_var_name] != df[, glb_rsp_var]
# if prediction is erroneous, measure predicted class prob from actual class prob
df[, predct_erabs_var_name] <- 0
for (cls in names(probCls)) {
mask <- (df[, glb_rsp_var] == cls) & (df[, predct_error_var_name])
df[mask, predct_erabs_var_name] <- probCls[mask, cls]
}
df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])
}
return(df)
}
#stop(here"); glb2Sav(); glbObsAll <- savObsAll; glbObsTrn <- savObsTrn; glbObsFit <- savObsFit; glbObsOOB <- savObsOOB; sav_models_df <- glb_models_df; glb_models_df <- sav_models_df; glb_featsimp_df <- sav_featsimp_df
myget_category_stats <- function(obs_df, mdl_id, label) {
require(dplyr)
require(lazyeval)
predct_var_name <- mygetPredictIds(glb_rsp_var, mdl_id)$value
predct_error_var_name <- mygetPredictIds(glb_rsp_var, mdl_id)$err.abs
if (!predct_var_name %in% names(obs_df))
obs_df <- glb_get_predictions(obs_df, mdl_id, glb_rsp_var)
tmp_obs_df <- obs_df[, c(glbFeatsCategory, glb_rsp_var,
predct_var_name, predct_error_var_name)]
# tmp_obs_df <- obs_df %>%
# dplyr::select_(glbFeatsCategory, glb_rsp_var, predct_var_name, predct_error_var_name)
#dplyr::rename(startprice.log10.predict.RFE.X.glmnet.err=error_abs_OOB)
names(tmp_obs_df)[length(names(tmp_obs_df))] <- paste0("err.abs.", label)
ret_ctgry_df <- tmp_obs_df %>%
dplyr::group_by_(glbFeatsCategory) %>%
dplyr::summarise_(#interp(~sum(abs(var)), var=as.name(glb_rsp_var)),
interp(~sum(var), var=as.name(paste0("err.abs.", label))),
interp(~mean(var), var=as.name(paste0("err.abs.", label))),
interp(~n()))
names(ret_ctgry_df) <- c(glbFeatsCategory,
#paste0(glb_rsp_var, ".abs.", label, ".sum"),
paste0("err.abs.", label, ".sum"),
paste0("err.abs.", label, ".mean"),
paste0(".n.", label))
ret_ctgry_df <- dplyr::ungroup(ret_ctgry_df)
#colSums(ret_ctgry_df[, -grep(glbFeatsCategory, names(ret_ctgry_df))])
return(ret_ctgry_df)
}
#print(colSums((ctgry_df <- myget_category_stats(obs_df=glbObsFit, mdl_id="", label="fit"))[, -grep(glbFeatsCategory, names(ctgry_df))]))
if (!is.null(glb_mdl_ensemble)) {
fit.models_2_chunk_df <- myadd_chunk(fit.models_2_chunk_df,
paste0("fit.models_2_", mdl_id_pfx), major.inc = TRUE,
label.minor = "ensemble")
mdl_id_pfx <- "Ensemble"
if (#(glb_is_regression) |
((glb_is_classification) & (!glb_is_binomial)))
stop("Ensemble models not implemented yet for multinomial classification")
mygetEnsembleAutoMdlIds <- function() {
tmp_models_df <- orderBy(get_model_sel_frmla(), glb_models_df)
row.names(tmp_models_df) <- tmp_models_df$id
mdl_threshold_pos <-
min(which(grepl("MFO|Random|Baseline", tmp_models_df$id))) - 1
mdlIds <- tmp_models_df$id[1:mdl_threshold_pos]
return(mdlIds[!grepl("Ensemble", mdlIds)])
}
if (glb_mdl_ensemble == "auto") {
glb_mdl_ensemble <- mygetEnsembleAutoMdlIds()
mdl_id_pfx <- paste0(mdl_id_pfx, ".auto")
} else if (grepl("^%<d-%", glb_mdl_ensemble)) {
glb_mdl_ensemble <- eval(parse(text =
str_trim(unlist(strsplit(glb_mdl_ensemble, "%<d-%"))[2])))
}
for (mdl_id in glb_mdl_ensemble) {
if (!(mdl_id %in% names(glb_models_lst))) {
warning("Model ", mdl_id, " in glb_model_ensemble not found !")
next
}
glbObsFit <- glb_get_predictions(df = glbObsFit, mdl_id, glb_rsp_var)
glbObsOOB <- glb_get_predictions(df = glbObsOOB, mdl_id, glb_rsp_var)
}
#mdl_id_pfx <- "Ensemble.RFE"; mdlId <- paste0(mdl_id_pfx, ".glmnet")
#glb_mdl_ensemble <- gsub(mygetPredictIds$value, "", grep("RFE\\.X\\.(?!Interact)", row.names(glb_featsimp_df), perl = TRUE, value = TRUE), fixed = TRUE)
#varImp(glb_models_lst[[mdlId]])
#cor_df <- data.frame(cor=cor(glbObsFit[, glb_rsp_var], glbObsFit[, paste(mygetPredictIds$value, glb_mdl_ensemble)], use="pairwise.complete.obs"))
#glbObsFit <- glb_get_predictions(df=glbObsFit, "Ensemble.glmnet", glb_rsp_var);print(colSums((ctgry_df <- myget_category_stats(obs_df=glbObsFit, mdl_id="Ensemble.glmnet", label="fit"))[, -grep(glbFeatsCategory, names(ctgry_df))]))
### bid0_sp
# Better than MFO; models.n=28; min.RMSE.fit=0.0521233; err.abs.fit.sum=7.3631895
# old: Top x from auto; models.n= 5; min.RMSE.fit=0.06311047; err.abs.fit.sum=9.5937080
# RFE only ; models.n=16; min.RMSE.fit=0.05148588; err.abs.fit.sum=7.2875091
# RFE subset only ;models.n= 5; min.RMSE.fit=0.06040702; err.abs.fit.sum=9.059088
# RFE subset only ;models.n= 9; min.RMSE.fit=0.05933167; err.abs.fit.sum=8.7421288
# RFE subset only ;models.n=15; min.RMSE.fit=0.0584607; err.abs.fit.sum=8.5902066
# RFE subset only ;models.n=17; min.RMSE.fit=0.05496899; err.abs.fit.sum=8.0170431
# RFE subset only ;models.n=18; min.RMSE.fit=0.05441577; err.abs.fit.sum=7.837223
# RFE subset only ;models.n=16; min.RMSE.fit=0.05441577; err.abs.fit.sum=7.837223
### bid0_sp
### bid1_sp
# "auto"; err.abs.fit.sum=76.699774; min.RMSE.fit=0.2186429
# "RFE.X.*"; err.abs.fit.sum=; min.RMSE.fit=0.221114
### bid1_sp
indep_vars <- paste(mygetPredictIds(glb_rsp_var)$value, glb_mdl_ensemble, sep = "")
if (glb_is_classification)
indep_vars <- paste(indep_vars, ".prob", sep = "")
# Some models in glb_mdl_ensemble might not be fitted e.g. RFE.X.Interact
indep_vars <- intersect(indep_vars, names(glbObsFit))
# indep_vars <- grep(mygetPredictIds(glb_rsp_var)$value, names(glbObsFit), fixed=TRUE, value=TRUE)
# if (glb_is_regression)
# indep_vars <- indep_vars[!grepl("(err\\.abs|accurate)$", indep_vars)]
# if (glb_is_classification && glb_is_binomial)
# indep_vars <- grep("prob$", indep_vars, value=TRUE) else
# indep_vars <- indep_vars[!grepl("err$", indep_vars)]
#rfe_fit_ens_results <- myrun_rfe(glbObsFit, indep_vars)
for (method in c("glm", "glmnet")) {
for (trainControlMethod in
c("boot", "boot632", "cv", "repeatedcv"
#, "LOOCV" # tuneLength * nrow(fitDF)
, "LGOCV", "adaptive_cv"
#, "adaptive_boot" #error: adaptive$min should be less than 3
#, "adaptive_LGOCV" #error: adaptive$min should be less than 3
)) {
#sav_models_df <- glb_models_df; all.equal(sav_models_df, glb_models_df)
#glb_models_df <- sav_models_df; print(glb_models_df$id)
if ((method == "glm") && (trainControlMethod != "repeatedcv"))
# glm used only to identify outliers
next
ret_lst <- myfit_mdl(
mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = paste0(mdl_id_pfx, ".", trainControlMethod),
type = glb_model_type, tune.df = NULL,
trainControl.method = trainControlMethod,
trainControl.number = glb_rcv_n_folds,
trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = method)),
indep_vars = indep_vars, rsp_var = glb_rsp_var,
fit_df = glbObsFit, OOB_df = glbObsOOB)
}
}
dsp_models_df <- get_dsp_models_df()
}
if (is.null(glb_sel_mdl_id))
glb_sel_mdl_id <- dsp_models_df[1, "id"] else
print(sprintf("User specified selection: %s", glb_sel_mdl_id))
## [1] "User specified selection: All.X##rcv#glmnet"
myprint_mdl(glb_sel_mdl <- glb_models_lst[[glb_sel_mdl_id]])
## Length Class Mode
## a0 20 -none- numeric
## beta 40 dgCMatrix S4
## df 20 -none- numeric
## dim 2 -none- numeric
## lambda 20 -none- numeric
## dev.ratio 20 -none- numeric
## nulldev 1 -none- numeric
## npasses 1 -none- numeric
## jerr 1 -none- numeric
## offset 1 -none- logical
## classnames 2 -none- character
## call 5 -none- call
## nobs 1 -none- numeric
## lambdaOpt 1 -none- numeric
## xNames 2 -none- character
## problemType 1 -none- character
## tuneValue 2 data.frame list
## obsLevels 2 -none- character
## [1] "min lambda > lambdaOpt:"
## (Intercept) .pos .rnorm
## -7.747964e-02 8.305337e-05 2.446781e-02
## [1] "max lambda < lambdaOpt:"
## [1] "Feats mismatch between coefs_left & rght:"
## [1] "(Intercept)" ".pos" ".rnorm"
## [1] TRUE
# From here to save(), this should all be in one function
# these are executed in the same seq twice more:
# fit.data.training & predict.data.new chunks
print(sprintf("%s fit prediction diagnostics:", glb_sel_mdl_id))
## [1] "All.X##rcv#glmnet fit prediction diagnostics:"
glbObsFit <- glb_get_predictions(df = glbObsFit, mdl_id = glb_sel_mdl_id,
rsp_var = glb_rsp_var)
print(sprintf("%s OOB prediction diagnostics:", glb_sel_mdl_id))
## [1] "All.X##rcv#glmnet OOB prediction diagnostics:"
glbObsOOB <- glb_get_predictions(df = glbObsOOB, mdl_id = glb_sel_mdl_id,
rsp_var = glb_rsp_var)
print(glb_featsimp_df <- myget_feats_importance(mdl = glb_sel_mdl, featsimp_df = NULL))
## All.X..rcv.glmnet.imp imp
## .rnorm 100 100
## .pos 0 0
#mdl_id <-"RFE.X.glmnet"; glb_featsimp_df <- myget_feats_importance(glb_models_lst[[mdl_id]], glb_featsimp_df); glb_featsimp_df[, paste0(mdl_id, ".imp")] <- glb_featsimp_df$imp; print(glb_featsimp_df)
#print(head(sbst_featsimp_df <- subset(glb_featsimp_df, is.na(RFE.X.glmnet.imp) | (abs(RFE.X.YeoJohnson.glmnet.imp - RFE.X.glmnet.imp) > 0.0001), select=-imp)))
#print(orderBy(~ -cor.y.abs, subset(glb_feats_df, id %in% c(row.names(sbst_featsimp_df), "startprice.dcm1.is9", "D.weight.post.stop.sum"))))
# Used again in fit.data.training & predict.data.new chunks
glb_analytics_diag_plots <- function(obs_df, mdl_id, prob_threshold=NULL) {
if (!is.null(featsimp_df <- glb_featsimp_df)) {
featsimp_df$feat <- gsub("`(.*?)`", "\\1", row.names(featsimp_df))
featsimp_df$feat.interact <- gsub("(.*?):(.*)", "\\2", featsimp_df$feat)
featsimp_df$feat <- gsub("(.*?):(.*)", "\\1", featsimp_df$feat)
featsimp_df$feat.interact <-
ifelse(featsimp_df$feat.interact == featsimp_df$feat,
NA, featsimp_df$feat.interact)
featsimp_df$feat <-
gsub("(.*?)\\.fctr(.*)", "\\1\\.fctr", featsimp_df$feat)
featsimp_df$feat.interact <-
gsub("(.*?)\\.fctr(.*)", "\\1\\.fctr", featsimp_df$feat.interact)
featsimp_df <- orderBy(~ -imp.max,
summaryBy(imp ~ feat + feat.interact, data=featsimp_df,
FUN=max))
#rex_str=":(.*)"; txt_vctr=tail(featsimp_df$feat); ret_lst <- regexec(rex_str, txt_vctr); ret_lst <- regmatches(txt_vctr, ret_lst); ret_vctr <- sapply(1:length(ret_lst), function(pos_ix) ifelse(length(ret_lst[[pos_ix]]) > 0, ret_lst[[pos_ix]], "")); print(ret_vctr <- ret_vctr[ret_vctr != ""])
featsimp_df <- subset(featsimp_df, !is.na(imp.max))
if (nrow(featsimp_df) > 5) {
warning("Limiting important feature scatter plots to 5 out of ",
nrow(featsimp_df))
featsimp_df <- head(featsimp_df, 5)
}
# if (!all(is.na(featsimp_df$feat.interact)))
# stop("not implemented yet")
rsp_var_out <- mygetPredictIds(glb_rsp_var, mdl_id)$value
for (var in featsimp_df$feat) {
plot_df <- melt(obs_df, id.vars = var,
measure.vars = c(glb_rsp_var, rsp_var_out))
print(myplot_scatter(plot_df, var, "value", colorcol_name = "variable",
facet_colcol_name = "variable", jitter = TRUE) +
guides(color = FALSE))
}
}
if (glb_is_regression) {
if (is.null(featsimp_df) || (nrow(featsimp_df) == 0))
warning("No important features in glb_fin_mdl") else
print(myplot_prediction_regression(df=obs_df,
feat_x=ifelse(nrow(featsimp_df) > 1, featsimp_df$feat[2],
".rownames"),
feat_y=featsimp_df$feat[1],
rsp_var=glb_rsp_var, rsp_var_out=rsp_var_out,
id_vars=glbFeatsId)
# + facet_wrap(reformulate(featsimp_df$feat[2])) # if [1 or 2] is a factor
# + geom_point(aes_string(color="<col_name>.fctr")) # to color the plot
)
}
if (glb_is_classification) {
if (is.null(featsimp_df) || (nrow(featsimp_df) == 0))
warning("No features in selected model are statistically important")
else print(myplot_prediction_classification(df = obs_df,
feat_x = ifelse(nrow(featsimp_df) > 1,
featsimp_df$feat[2], ".rownames"),
feat_y = featsimp_df$feat[1],
rsp_var = glb_rsp_var,
rsp_var_out = rsp_var_out,
id_vars = glbFeatsId,
prob_threshold = prob_threshold))
}
}
if (glb_is_classification && glb_is_binomial)
glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id,
prob_threshold = glb_models_df[glb_models_df$id == glb_sel_mdl_id,
"opt.prob.threshold.OOB"]) else
glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id)
## [1] "Min/Max Boundaries: "
## business_id outdoor.fctr outdoor.fctr.All.X..rcv.glmnet.prob
## 1 1000 Y 0.4777288
## 2 3628 Y 0.5335303
## 3 3024 N 0.4849593
## 4 999 N 0.5249562
## outdoor.fctr.All.X..rcv.glmnet outdoor.fctr.All.X..rcv.glmnet.err
## 1 Y FALSE
## 2 Y FALSE
## 3 Y TRUE
## 4 Y TRUE
## outdoor.fctr.All.X..rcv.glmnet.err.abs
## 1 0.5222712
## 2 0.4664697
## 3 0.4849593
## 4 0.5249562
## outdoor.fctr.All.X..rcv.glmnet.is.acc
## 1 TRUE
## 2 TRUE
## 3 FALSE
## 4 FALSE
## outdoor.fctr.All.X..rcv.glmnet.accurate
## 1 TRUE
## 2 TRUE
## 3 FALSE
## 4 FALSE
## outdoor.fctr.All.X..rcv.glmnet.error .label
## 1 0.00000000 1000
## 2 0.00000000 3628
## 3 0.08495926 3024
## 4 0.12495619 999
## [1] "Inaccurate: "
## business_id outdoor.fctr outdoor.fctr.All.X..rcv.glmnet.prob
## 1 1140 N 0.4707643
## 2 1114 N 0.4719215
## 3 1283 N 0.4741398
## 4 135 N 0.4745672
## 5 1565 N 0.4747244
## 6 1447 N 0.4747875
## outdoor.fctr.All.X..rcv.glmnet outdoor.fctr.All.X..rcv.glmnet.err
## 1 Y TRUE
## 2 Y TRUE
## 3 Y TRUE
## 4 Y TRUE
## 5 Y TRUE
## 6 Y TRUE
## outdoor.fctr.All.X..rcv.glmnet.err.abs
## 1 0.4707643
## 2 0.4719215
## 3 0.4741398
## 4 0.4745672
## 5 0.4747244
## 6 0.4747875
## outdoor.fctr.All.X..rcv.glmnet.is.acc
## 1 FALSE
## 2 FALSE
## 3 FALSE
## 4 FALSE
## 5 FALSE
## 6 FALSE
## outdoor.fctr.All.X..rcv.glmnet.accurate
## 1 FALSE
## 2 FALSE
## 3 FALSE
## 4 FALSE
## 5 FALSE
## 6 FALSE
## outdoor.fctr.All.X..rcv.glmnet.error
## 1 0.07076434
## 2 0.07192152
## 3 0.07413979
## 4 0.07456722
## 5 0.07472435
## 6 0.07478747
## business_id outdoor.fctr outdoor.fctr.All.X..rcv.glmnet.prob
## 96 1469 N 0.4884968
## 180 2892 N 0.4946561
## 317 3582 N 0.5067863
## 358 3216 N 0.5104651
## 439 540 N 0.5188407
## 463 3320 N 0.5220728
## outdoor.fctr.All.X..rcv.glmnet outdoor.fctr.All.X..rcv.glmnet.err
## 96 Y TRUE
## 180 Y TRUE
## 317 Y TRUE
## 358 Y TRUE
## 439 Y TRUE
## 463 Y TRUE
## outdoor.fctr.All.X..rcv.glmnet.err.abs
## 96 0.4884968
## 180 0.4946561
## 317 0.5067863
## 358 0.5104651
## 439 0.5188407
## 463 0.5220728
## outdoor.fctr.All.X..rcv.glmnet.is.acc
## 96 FALSE
## 180 FALSE
## 317 FALSE
## 358 FALSE
## 439 FALSE
## 463 FALSE
## outdoor.fctr.All.X..rcv.glmnet.accurate
## 96 FALSE
## 180 FALSE
## 317 FALSE
## 358 FALSE
## 439 FALSE
## 463 FALSE
## outdoor.fctr.All.X..rcv.glmnet.error
## 96 0.08849675
## 180 0.09465609
## 317 0.10678625
## 358 0.11046512
## 439 0.11884075
## 463 0.12207278
## business_id outdoor.fctr outdoor.fctr.All.X..rcv.glmnet.prob
## 493 549 N 0.5291702
## 494 8 N 0.5292651
## 495 929 N 0.5298729
## 496 841 N 0.5315117
## 497 662 N 0.5325720
## 498 732 N 0.5335520
## outdoor.fctr.All.X..rcv.glmnet outdoor.fctr.All.X..rcv.glmnet.err
## 493 Y TRUE
## 494 Y TRUE
## 495 Y TRUE
## 496 Y TRUE
## 497 Y TRUE
## 498 Y TRUE
## outdoor.fctr.All.X..rcv.glmnet.err.abs
## 493 0.5291702
## 494 0.5292651
## 495 0.5298729
## 496 0.5315117
## 497 0.5325720
## 498 0.5335520
## outdoor.fctr.All.X..rcv.glmnet.is.acc
## 493 FALSE
## 494 FALSE
## 495 FALSE
## 496 FALSE
## 497 FALSE
## 498 FALSE
## outdoor.fctr.All.X..rcv.glmnet.accurate
## 493 FALSE
## 494 FALSE
## 495 FALSE
## 496 FALSE
## 497 FALSE
## 498 FALSE
## outdoor.fctr.All.X..rcv.glmnet.error
## 493 0.1291702
## 494 0.1292651
## 495 0.1298729
## 496 0.1315117
## 497 0.1325720
## 498 0.1335520
if (!is.null(glbFeatsCategory)) {
glbLvlCategory <- merge(glbLvlCategory,
myget_category_stats(obs_df = glbObsFit, mdl_id = glb_sel_mdl_id,
label = "fit"),
by = glbFeatsCategory, all = TRUE)
row.names(glbLvlCategory) <- glbLvlCategory[, glbFeatsCategory]
glbLvlCategory <- merge(glbLvlCategory,
myget_category_stats(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id,
label="OOB"),
#by=glbFeatsCategory, all=TRUE) glb_ctgry-df already contains .n.OOB ?
all = TRUE)
row.names(glbLvlCategory) <- glbLvlCategory[, glbFeatsCategory]
if (any(grepl("OOB", glbMdlMetricsEval)))
print(orderBy(~-err.abs.OOB.mean, glbLvlCategory)) else
print(orderBy(~-err.abs.fit.mean, glbLvlCategory))
print(colSums(glbLvlCategory[, -grep(glbFeatsCategory, names(glbLvlCategory))]))
}
## .category .n.OOB .n.Fit .n.Tst .freqRatio.Fit .freqRatio.OOB
## .dummy .dummy 999 1001 10000 1 1
## .freqRatio.Tst err.abs.fit.sum err.abs.fit.mean .n.fit
## .dummy 1 500.017 0.4995175 1001
## err.abs.OOB.sum err.abs.OOB.mean
## .dummy 499.4153 0.4999153
## .n.OOB .n.Fit .n.Tst .freqRatio.Fit
## 9.990000e+02 1.001000e+03 1.000000e+04 1.000000e+00
## .freqRatio.OOB .freqRatio.Tst err.abs.fit.sum err.abs.fit.mean
## 1.000000e+00 1.000000e+00 5.000170e+02 4.995175e-01
## .n.fit err.abs.OOB.sum err.abs.OOB.mean
## 1.001000e+03 4.994153e+02 4.999153e-01
write.csv(glbObsOOB[, c(glbFeatsId,
grep(glb_rsp_var, names(glbObsOOB), fixed=TRUE, value=TRUE))],
paste0(gsub(".", "_", paste0(glbOut$pfx, glb_sel_mdl_id), fixed=TRUE),
"_OOBobs.csv"), row.names=FALSE)
fit.models_2_chunk_df <-
myadd_chunk(NULL, "fit.models_2_bgn", label.minor = "teardown")
## label step_major step_minor label_minor bgn end elapsed
## 1 fit.models_2_bgn 1 0 teardown 92.738 NA NA
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc=FALSE)
## label step_major step_minor label_minor bgn end elapsed
## 18 fit.models 8 2 2 84.050 92.748 8.698
## 19 fit.models 8 3 3 92.749 NA NA
# if (sum(is.na(glbObsAll$D.P.http)) > 0)
# stop("fit.models_3: Why is this happening ?")
#stop(here"); glb2Sav()
sync_glb_obs_df <- function() {
# Merge or cbind ?
for (col in setdiff(names(glbObsFit), names(glbObsTrn)))
glbObsTrn[glbObsTrn$.lcn == "Fit", col] <<- glbObsFit[, col]
for (col in setdiff(names(glbObsFit), names(glbObsAll)))
glbObsAll[glbObsAll$.lcn == "Fit", col] <<- glbObsFit[, col]
if (all(is.na(glbObsNew[, glb_rsp_var])))
for (col in setdiff(names(glbObsOOB), names(glbObsTrn)))
glbObsTrn[glbObsTrn$.lcn == "OOB", col] <<- glbObsOOB[, col]
for (col in setdiff(names(glbObsOOB), names(glbObsAll)))
glbObsAll[glbObsAll$.lcn == "OOB", col] <<- glbObsOOB[, col]
}
sync_glb_obs_df()
print(setdiff(names(glbObsNew), names(glbObsAll)))
## character(0)
replay.petrisim(pn=glb_analytics_pn,
replay.trans=(glb_analytics_avl_objs <- c(glb_analytics_avl_objs,
"model.selected")), flip_coord=TRUE)
## time trans "bgn " "fit.data.training.all " "predict.data.new " "end "
## 0.0000 multiple enabled transitions: data.training.all data.new model.selected firing: data.training.all
## 1.0000 1 2 1 0 0
## 1.0000 multiple enabled transitions: data.training.all data.new model.selected model.final data.training.all.prediction firing: data.new
## 2.0000 2 1 1 1 0
## 2.0000 multiple enabled transitions: data.training.all data.new model.selected model.final data.training.all.prediction data.new.prediction firing: model.selected
## 3.0000 3 0 2 1 0
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.data.training", major.inc = TRUE)
## label step_major step_minor label_minor bgn end
## 19 fit.models 8 3 3 92.749 95.986
## 20 fit.data.training 9 0 0 95.986 NA
## elapsed
## 19 3.237
## 20 NA
9.0: fit data training#load(paste0(glb_inp_pfx, "dsk.RData"))
if (!is.null(glb_fin_mdl_id) && (glb_fin_mdl_id %in% names(glb_models_lst))) {
warning("Final model same as user selected model")
glb_fin_mdl <- glb_models_lst[[glb_fin_mdl_id]]
} else
# if (nrow(glbObsFit) + length(glbObsFitOutliers) == nrow(glbObsTrn))
if (!all(is.na(glbObsNew[, glb_rsp_var])))
{
warning("Final model same as glb_sel_mdl_id")
glb_fin_mdl_id <- paste0("Final.", glb_sel_mdl_id)
glb_fin_mdl <- glb_sel_mdl
glb_models_lst[[glb_fin_mdl_id]] <- glb_fin_mdl
} else {
if (grepl("RFE\\.X", names(glbMdlFamilies))) {
indep_vars <- myadjust_interaction_feats(subset(glb_feats_df,
!nzv & (exclude.as.feat != 1))[, "id"])
rfe_trn_results <-
myrun_rfe(glbObsTrn, indep_vars, glbRFESizes[["Final"]])
if (!isTRUE(all.equal(sort(predictors(rfe_trn_results)),
sort(predictors(rfe_fit_results))))) {
print("Diffs predictors(rfe_trn_results) vs. predictors(rfe_fit_results):")
print(setdiff(predictors(rfe_trn_results), predictors(rfe_fit_results)))
print("Diffs predictors(rfe_fit_results) vs. predictors(rfe_trn_results):")
print(setdiff(predictors(rfe_fit_results), predictors(rfe_trn_results)))
}
}
# }
if (grepl("Ensemble", glb_sel_mdl_id)) {
# Find which models are relevant
mdlimp_df <- subset(myget_feats_importance(glb_sel_mdl), imp > 5)
# Fit selected models on glbObsTrn
for (mdl_id in gsub(".prob", "",
gsub(mygetPredictIds(glb_rsp_var)$value, "", row.names(mdlimp_df), fixed = TRUE),
fixed = TRUE)) {
mdl_id_components <- unlist(strsplit(mdl_id, "[.]"))
mdlIdPfx <- paste0(c(head(mdl_id_components, -1), "Train"),
collapse = ".")
if (grepl("RFE\\.X\\.", mdlIdPfx))
mdlIndepVars <- myadjust_interaction_feats(myextract_actual_feats(
predictors(rfe_trn_results))) else
mdlIndepVars <- trim(unlist(
strsplit(glb_models_df[glb_models_df$id == mdl_id, "feats"], "[,]")))
ret_lst <-
myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = mdlIdPfx,
type = glb_model_type, tune.df = glbMdlTuneParams,
trainControl.method = "repeatedcv",
trainControl.number = glb_rcv_n_folds,
trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = tail(mdl_id_components, 1))),
indep_vars = mdlIndepVars,
rsp_var = glb_rsp_var,
fit_df = glbObsTrn, OOB_df = NULL)
glbObsTrn <- glb_get_predictions(df = glbObsTrn,
mdl_id = tail(glb_models_df$id, 1),
rsp_var = glb_rsp_var,
prob_threshold_def =
subset(glb_models_df, id == mdl_id)$opt.prob.threshold.OOB)
glbObsNew <- glb_get_predictions(df = glbObsNew,
mdl_id = tail(glb_models_df$id, 1),
rsp_var = glb_rsp_var,
prob_threshold_def =
subset(glb_models_df, id == mdl_id)$opt.prob.threshold.OOB)
}
}
# "Final" model
if ((model_method <- glb_sel_mdl$method) == "custom")
# get actual method from the mdl_id
model_method <- tail(unlist(strsplit(glb_sel_mdl_id, "[.]")), 1)
if (grepl("Ensemble", glb_sel_mdl_id)) {
# Find which models are relevant
mdlimp_df <- subset(myget_feats_importance(glb_sel_mdl), imp > 5)
if (glb_is_classification && glb_is_binomial)
indep_vars_vctr <- gsub("(.*)\\.(.*)\\.prob", "\\1\\.Train\\.\\2\\.prob",
row.names(mdlimp_df)) else
indep_vars_vctr <- gsub("(.*)\\.(.*)", "\\1\\.Train\\.\\2",
row.names(mdlimp_df))
} else
if (grepl("RFE.X", glb_sel_mdl_id, fixed = TRUE)) {
indep_vars_vctr <- myextract_actual_feats(predictors(rfe_trn_results))
} else indep_vars_vctr <-
trim(unlist(strsplit(glb_models_df[glb_models_df$id ==
glb_sel_mdl_id
, "feats"], "[,]")))
if (!is.null(glb_preproc_methods) &&
((match_pos <- regexpr(gsub(".", "\\.",
paste(glb_preproc_methods, collapse = "|"),
fixed = TRUE), glb_sel_mdl_id)) != -1))
ths_preProcess <- str_sub(glb_sel_mdl_id, match_pos,
match_pos + attr(match_pos, "match.length") - 1) else
ths_preProcess <- NULL
mdl_id_pfx <- ifelse(grepl("Ensemble", glb_sel_mdl_id),
"Final.Ensemble", "Final")
trnobs_df <- glbObsTrn
if (!is.null(glbObsTrnOutliers[[mdl_id_pfx]])) {
trnobs_df <- glbObsTrn[!(glbObsTrn[, glbFeatsId] %in% glbObsTrnOutliers[[mdl_id_pfx]]), ]
print(sprintf("Outliers removed: %d", nrow(glbObsTrn) - nrow(trnobs_df)))
print(setdiff(glbObsTrn[, glbFeatsId], trnobs_df[, glbFeatsId]))
}
# Force fitting of Final.glm to identify outliers
method_vctr <- unique(c(myparseMdlId(glb_sel_mdl_id)$alg, glbMdlFamilies[["Final"]]))
for (method in method_vctr) {
#source("caret_nominalTrainWorkflow.R")
# glmnet requires at least 2 indep vars
if ((length(indep_vars_vctr) == 1) && (method %in% "glmnet"))
next
ret_lst <-
myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
id.prefix = mdl_id_pfx,
type = glb_model_type, trainControl.method = "repeatedcv",
trainControl.number = glb_rcv_n_folds,
trainControl.repeats = glb_rcv_n_repeats,
trainControl.classProbs = glb_is_classification,
trainControl.summaryFunction = glbMdlMetricSummaryFn,
trainControl.allowParallel = glbMdlAllowParallel,
train.metric = glbMdlMetricSummary,
train.maximize = glbMdlMetricMaximize,
train.method = method,
train.preProcess = ths_preProcess)),
indep_vars = indep_vars_vctr, rsp_var = glb_rsp_var,
fit_df = trnobs_df, OOB_df = NULL)
if ((length(method_vctr) == 1) || (method != "glm")) {
glb_fin_mdl <- glb_models_lst[[length(glb_models_lst)]]
glb_fin_mdl_id <- glb_models_df[length(glb_models_lst), "id"]
}
}
}
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Final##rcv#glmnet"
## [1] " indep_vars: .pos,.rnorm"
## [1] "myfit_mdl: setup complete: 0.728000 secs"
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 0.325, lambda = 0.00592 on full training set
## [1] "myfit_mdl: train complete: 3.738000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = mdl_id_pfx, : model's bestTune found at an extreme of
## tuneGrid for parameter: lambda
## Length Class Mode
## a0 19 -none- numeric
## beta 38 dgCMatrix S4
## df 19 -none- numeric
## dim 2 -none- numeric
## lambda 19 -none- numeric
## dev.ratio 19 -none- numeric
## nulldev 1 -none- numeric
## npasses 1 -none- numeric
## jerr 1 -none- numeric
## offset 1 -none- logical
## classnames 2 -none- character
## call 5 -none- call
## nobs 1 -none- numeric
## lambdaOpt 1 -none- numeric
## xNames 2 -none- character
## problemType 1 -none- character
## tuneValue 2 data.frame list
## obsLevels 2 -none- character
## [1] "min lambda > lambdaOpt:"
## (Intercept) .pos .rnorm
## -7.019218e-02 7.617623e-05 -6.889245e-03
## [1] "max lambda < lambdaOpt:"
## [1] "Feats mismatch between coefs_left & rght:"
## [1] "(Intercept)" ".pos" ".rnorm"
## [1] "myfit_mdl: train diagnostics complete: 4.280000 secs"
## Prediction
## Reference N Y
## N 0 997
## Y 0 1003
## Accuracy Kappa AccuracyLower AccuracyUpper AccuracyNull
## 5.015000e-01 0.000000e+00 4.793485e-01 5.236471e-01 5.015000e-01
## AccuracyPValue McnemarPValue
## 5.089285e-01 2.192151e-218
## [1] "myfit_mdl: predict complete: 6.083000 secs"
## id feats max.nTuningRuns min.elapsedtime.everything
## 1 Final##rcv#glmnet .pos,.rnorm 15 3.004
## min.elapsedtime.final max.AUCpROC.fit max.Sens.fit max.Spec.fit
## 1 0.011 0.5088876 0.4714142 0.5463609
## max.AUCROCR.fit opt.prob.threshold.fit max.f.score.fit max.Accuracy.fit
## 1 0.5153906 0.4 0.6679987 0.4983234
## max.AccuracyLower.fit max.AccuracyUpper.fit max.Kappa.fit
## 1 0.4793485 0.5236471 -0.003762271
## max.AccuracySD.fit max.KappaSD.fit
## 1 0.01707848 0.03401531
## [1] "myfit_mdl: exit: 6.100000 secs"
rm(ret_lst)
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.data.training", major.inc=FALSE)
## label step_major step_minor label_minor bgn end
## 20 fit.data.training 9 0 0 95.986 102.605
## 21 fit.data.training 9 1 1 102.606 NA
## elapsed
## 20 6.619
## 21 NA
#stop(here"); glb2Sav()
if (glb_is_classification && glb_is_binomial)
prob_threshold <- glb_models_df[glb_models_df$id == glb_sel_mdl_id,
"opt.prob.threshold.OOB"] else
prob_threshold <- NULL
if (grepl("Ensemble", glb_fin_mdl_id)) {
# Get predictions for each model in ensemble; Outliers that have been moved to OOB might not have been predicted yet
mdlEnsembleComps <- unlist(str_split(subset(glb_models_df,
id == glb_fin_mdl_id)$feats, ","))
if (glb_is_classification && glb_is_binomial)
mdlEnsembleComps <- gsub("\\.prob$", "", mdlEnsembleComps)
mdlEnsembleComps <- gsub(paste0("^",
gsub(".", "\\.", mygetPredictIds(glb_rsp_var)$value, fixed = TRUE)),
"", mdlEnsembleComps)
for (mdl_id in mdlEnsembleComps) {
glbObsTrn <- glb_get_predictions(df = glbObsTrn, mdl_id = mdl_id,
rsp_var = glb_rsp_var,
prob_threshold_def = prob_threshold)
glbObsNew <- glb_get_predictions(df = glbObsNew, mdl_id = mdl_id,
rsp_var = glb_rsp_var,
prob_threshold_def = prob_threshold)
}
}
glbObsTrn <- glb_get_predictions(df = glbObsTrn, mdl_id = glb_fin_mdl_id,
rsp_var = glb_rsp_var,
prob_threshold_def = prob_threshold)
## Warning in glb_get_predictions(df = glbObsTrn, mdl_id = glb_fin_mdl_id, :
## Using default probability threshold: 0.4
glb_featsimp_df <- myget_feats_importance(mdl=glb_fin_mdl,
featsimp_df=glb_featsimp_df)
#glb_featsimp_df[, paste0(glb_fin_mdl_id, ".imp")] <- glb_featsimp_df$imp
print(glb_featsimp_df)
## All.X..rcv.glmnet.imp Final..rcv.glmnet.imp imp
## .rnorm 100 100 100
## .pos 0 0 0
if (glb_is_classification && glb_is_binomial)
glb_analytics_diag_plots(obs_df=glbObsTrn, mdl_id=glb_fin_mdl_id,
prob_threshold=glb_models_df[glb_models_df$id == glb_sel_mdl_id,
"opt.prob.threshold.OOB"]) else
glb_analytics_diag_plots(obs_df=glbObsTrn, mdl_id=glb_fin_mdl_id)
## [1] "Min/Max Boundaries: "
## business_id outdoor.fctr outdoor.fctr.All.X..rcv.glmnet.prob
## 1 1000 Y NA
## 2 3628 Y NA
## 3 999 N NA
## 4 563 N 0.4957591
## outdoor.fctr.All.X..rcv.glmnet outdoor.fctr.All.X..rcv.glmnet.err
## 1 <NA> NA
## 2 <NA> NA
## 3 <NA> NA
## 4 Y TRUE
## outdoor.fctr.All.X..rcv.glmnet.err.abs
## 1 NA
## 2 NA
## 3 NA
## 4 0.4957591
## outdoor.fctr.All.X..rcv.glmnet.is.acc
## 1 NA
## 2 NA
## 3 NA
## 4 FALSE
## outdoor.fctr.Final..rcv.glmnet.prob outdoor.fctr.Final..rcv.glmnet
## 1 0.4833041 Y
## 2 0.5035591 Y
## 3 0.5197358 Y
## 4 0.5216868 Y
## outdoor.fctr.Final..rcv.glmnet.err
## 1 FALSE
## 2 FALSE
## 3 TRUE
## 4 TRUE
## outdoor.fctr.Final..rcv.glmnet.err.abs
## 1 0.5166959
## 2 0.4964409
## 3 0.5197358
## 4 0.5216868
## outdoor.fctr.Final..rcv.glmnet.is.acc
## 1 TRUE
## 2 TRUE
## 3 FALSE
## 4 FALSE
## outdoor.fctr.Final..rcv.glmnet.accurate
## 1 TRUE
## 2 TRUE
## 3 FALSE
## 4 FALSE
## outdoor.fctr.Final..rcv.glmnet.error .label
## 1 0.0000000 1000
## 2 0.0000000 3628
## 3 0.1197358 999
## 4 0.1216868 563
## [1] "Inaccurate: "
## business_id outdoor.fctr outdoor.fctr.All.X..rcv.glmnet.prob
## 1 100 N 0.4961394
## 2 1169 N NA
## 3 1040 N 0.4925959
## 4 1014 N NA
## 5 1001 N NA
## 6 1036 N 0.4906093
## outdoor.fctr.All.X..rcv.glmnet outdoor.fctr.All.X..rcv.glmnet.err
## 1 Y TRUE
## 2 <NA> NA
## 3 Y TRUE
## 4 <NA> NA
## 5 <NA> NA
## 6 Y TRUE
## outdoor.fctr.All.X..rcv.glmnet.err.abs
## 1 0.4961394
## 2 NA
## 3 0.4925959
## 4 NA
## 5 NA
## 6 0.4906093
## outdoor.fctr.All.X..rcv.glmnet.is.acc
## 1 FALSE
## 2 NA
## 3 FALSE
## 4 NA
## 5 NA
## 6 FALSE
## outdoor.fctr.Final..rcv.glmnet.prob outdoor.fctr.Final..rcv.glmnet
## 1 0.4781737 Y
## 2 0.4785760 Y
## 3 0.4796915 Y
## 4 0.4799674 Y
## 5 0.4800291 Y
## 6 0.4801756 Y
## outdoor.fctr.Final..rcv.glmnet.err
## 1 TRUE
## 2 TRUE
## 3 TRUE
## 4 TRUE
## 5 TRUE
## 6 TRUE
## outdoor.fctr.Final..rcv.glmnet.err.abs
## 1 0.4781737
## 2 0.4785760
## 3 0.4796915
## 4 0.4799674
## 5 0.4800291
## 6 0.4801756
## outdoor.fctr.Final..rcv.glmnet.is.acc
## 1 FALSE
## 2 FALSE
## 3 FALSE
## 4 FALSE
## 5 FALSE
## 6 FALSE
## outdoor.fctr.Final..rcv.glmnet.accurate
## 1 FALSE
## 2 FALSE
## 3 FALSE
## 4 FALSE
## 5 FALSE
## 6 FALSE
## outdoor.fctr.Final..rcv.glmnet.error
## 1 0.07817368
## 2 0.07857596
## 3 0.07969151
## 4 0.07996742
## 5 0.08002908
## 6 0.08017559
## business_id outdoor.fctr outdoor.fctr.All.X..rcv.glmnet.prob
## 16 1133 N 0.4910914
## 17 1201 N NA
## 217 1759 N 0.4918581
## 274 1730 N NA
## 411 2554 N NA
## 496 2707 N NA
## outdoor.fctr.All.X..rcv.glmnet outdoor.fctr.All.X..rcv.glmnet.err
## 16 Y TRUE
## 17 <NA> NA
## 217 Y TRUE
## 274 <NA> NA
## 411 <NA> NA
## 496 <NA> NA
## outdoor.fctr.All.X..rcv.glmnet.err.abs
## 16 0.4910914
## 17 NA
## 217 0.4918581
## 274 NA
## 411 NA
## 496 NA
## outdoor.fctr.All.X..rcv.glmnet.is.acc
## 16 FALSE
## 17 NA
## 217 FALSE
## 274 NA
## 411 NA
## 496 NA
## outdoor.fctr.Final..rcv.glmnet.prob outdoor.fctr.Final..rcv.glmnet
## 16 0.4816058 Y
## 17 0.4816081 Y
## 217 0.4905672 Y
## 274 0.4925570 Y
## 411 0.4979081 Y
## 496 0.5008315 Y
## outdoor.fctr.Final..rcv.glmnet.err
## 16 TRUE
## 17 TRUE
## 217 TRUE
## 274 TRUE
## 411 TRUE
## 496 TRUE
## outdoor.fctr.Final..rcv.glmnet.err.abs
## 16 0.4816058
## 17 0.4816081
## 217 0.4905672
## 274 0.4925570
## 411 0.4979081
## 496 0.5008315
## outdoor.fctr.Final..rcv.glmnet.is.acc
## 16 FALSE
## 17 FALSE
## 217 FALSE
## 274 FALSE
## 411 FALSE
## 496 FALSE
## outdoor.fctr.Final..rcv.glmnet.accurate
## 16 FALSE
## 17 FALSE
## 217 FALSE
## 274 FALSE
## 411 FALSE
## 496 FALSE
## outdoor.fctr.Final..rcv.glmnet.error
## 16 0.08160579
## 17 0.08160810
## 217 0.09056717
## 274 0.09255697
## 411 0.09790812
## 496 0.10083153
## business_id outdoor.fctr outdoor.fctr.All.X..rcv.glmnet.prob
## 992 563 N 0.4957591
## 993 856 N NA
## 994 941 N NA
## 995 913 N 0.5123572
## 996 939 N 0.5106747
## 997 998 N 0.5130993
## outdoor.fctr.All.X..rcv.glmnet outdoor.fctr.All.X..rcv.glmnet.err
## 992 Y TRUE
## 993 <NA> NA
## 994 <NA> NA
## 995 Y TRUE
## 996 Y TRUE
## 997 Y TRUE
## outdoor.fctr.All.X..rcv.glmnet.err.abs
## 992 0.4957591
## 993 NA
## 994 NA
## 995 0.5123572
## 996 0.5106747
## 997 0.5130993
## outdoor.fctr.All.X..rcv.glmnet.is.acc
## 992 FALSE
## 993 NA
## 994 NA
## 995 FALSE
## 996 FALSE
## 997 FALSE
## outdoor.fctr.Final..rcv.glmnet.prob outdoor.fctr.Final..rcv.glmnet
## 992 0.5216868 Y
## 993 0.5219230 Y
## 994 0.5220583 Y
## 995 0.5220895 Y
## 996 0.5229847 Y
## 997 0.5230483 Y
## outdoor.fctr.Final..rcv.glmnet.err
## 992 TRUE
## 993 TRUE
## 994 TRUE
## 995 TRUE
## 996 TRUE
## 997 TRUE
## outdoor.fctr.Final..rcv.glmnet.err.abs
## 992 0.5216868
## 993 0.5219230
## 994 0.5220583
## 995 0.5220895
## 996 0.5229847
## 997 0.5230483
## outdoor.fctr.Final..rcv.glmnet.is.acc
## 992 FALSE
## 993 FALSE
## 994 FALSE
## 995 FALSE
## 996 FALSE
## 997 FALSE
## outdoor.fctr.Final..rcv.glmnet.accurate
## 992 FALSE
## 993 FALSE
## 994 FALSE
## 995 FALSE
## 996 FALSE
## 997 FALSE
## outdoor.fctr.Final..rcv.glmnet.error
## 992 0.1216868
## 993 0.1219230
## 994 0.1220583
## 995 0.1220895
## 996 0.1229847
## 997 0.1230483
dsp_feats_vctr <- c(NULL)
for(var in grep(".imp", names(glb_feats_df), fixed=TRUE, value=TRUE))
dsp_feats_vctr <- union(dsp_feats_vctr,
glb_feats_df[!is.na(glb_feats_df[, var]), "id"])
# print(glbObsTrn[glbObsTrn$UniqueID %in% FN_OOB_ids,
# grep(glb_rsp_var, names(glbObsTrn), value=TRUE)])
print(setdiff(names(glbObsTrn), names(glbObsAll)))
## [1] "outdoor.fctr.Final..rcv.glmnet.prob"
## [2] "outdoor.fctr.Final..rcv.glmnet"
## [3] "outdoor.fctr.Final..rcv.glmnet.err"
## [4] "outdoor.fctr.Final..rcv.glmnet.err.abs"
## [5] "outdoor.fctr.Final..rcv.glmnet.is.acc"
for (col in setdiff(names(glbObsTrn), names(glbObsAll)))
# Merge or cbind ?
glbObsAll[glbObsAll$.src == "Train", col] <- glbObsTrn[, col]
print(setdiff(names(glbObsFit), names(glbObsAll)))
## character(0)
print(setdiff(names(glbObsOOB), names(glbObsAll)))
## character(0)
for (col in setdiff(names(glbObsOOB), names(glbObsAll)))
# Merge or cbind ?
glbObsAll[glbObsAll$.lcn == "OOB", col] <- glbObsOOB[, col]
print(setdiff(names(glbObsNew), names(glbObsAll)))
## character(0)
#glb2Sav(); all.equal(savObsAll, glbObsAll); all.equal(sav_models_lst, glb_models_lst)
#load(file = paste0(glbOut$pfx, "dsk_knitr.RData"))
#cmpCols <- names(glbObsAll)[!grepl("\\.Final\\.", names(glbObsAll))]; all.equal(savObsAll[, cmpCols], glbObsAll[, cmpCols]); all.equal(savObsAll[, "H.P.http"], glbObsAll[, "H.P.http"]);
replay.petrisim(pn = glb_analytics_pn,
replay.trans = (glb_analytics_avl_objs <- c(glb_analytics_avl_objs,
"data.training.all.prediction","model.final")), flip_coord = TRUE)
## time trans "bgn " "fit.data.training.all " "predict.data.new " "end "
## 0.0000 multiple enabled transitions: data.training.all data.new model.selected firing: data.training.all
## 1.0000 1 2 1 0 0
## 1.0000 multiple enabled transitions: data.training.all data.new model.selected model.final data.training.all.prediction firing: data.new
## 2.0000 2 1 1 1 0
## 2.0000 multiple enabled transitions: data.training.all data.new model.selected model.final data.training.all.prediction data.new.prediction firing: model.selected
## 3.0000 3 0 2 1 0
## 3.0000 multiple enabled transitions: model.final data.training.all.prediction data.new.prediction firing: data.training.all.prediction
## 4.0000 5 0 1 1 1
## 4.0000 multiple enabled transitions: model.final data.training.all.prediction data.new.prediction firing: model.final
## 5.0000 4 0 0 2 1
glb_chunks_df <- myadd_chunk(glb_chunks_df, "predict.data.new", major.inc = TRUE)
## label step_major step_minor label_minor bgn end
## 21 fit.data.training 9 1 1 102.606 107.228
## 22 predict.data.new 10 0 0 107.229 NA
## elapsed
## 21 4.622
## 22 NA
10.0: predict data new## Warning in glb_get_predictions(obs_df, mdl_id = glb_fin_mdl_id, rsp_var =
## glb_rsp_var, : Using default probability threshold: 0.4
## Warning in glb_get_predictions(obs_df, mdl_id = glb_fin_mdl_id, rsp_var =
## glb_rsp_var, : Using default probability threshold: 0.4
## Warning: Removed 10000 rows containing missing values (geom_point).
## Warning: Removed 10000 rows containing missing values (geom_point).
## Warning: Removed 10000 rows containing missing values (geom_point).
## Warning: Removed 10000 rows containing missing values (geom_point).
## NULL
## Loading required package: tidyr
##
## Attaching package: 'tidyr'
## The following object is masked from 'package:Matrix':
##
## expand
## [1] "OOBobs outdoor.fctr.All.X..rcv.glmnet Y: min < min of Train range: 2"
## business_id outdoor.fctr.All.X..rcv.glmnet .pos
## 2 1001 Y 2
## 1 1000 Y 1
## id cor.y exclude.as.feat cor.y.abs cor.high.X freqRatio
## .pos .pos 0.0274973 FALSE 0.0274973 NA 1
## percentUnique zeroVar nzv is.cor.y.abs.low interaction.feat
## .pos 100 FALSE FALSE FALSE NA
## shapiro.test.p.value rsp_var_raw id_var rsp_var max min
## .pos 2.145811e-24 FALSE NA NA 12000 1
## max.outdoor.fctr.N max.outdoor.fctr.Y min.outdoor.fctr.N
## .pos 1999 1996 3
## min.outdoor.fctr.Y max.outdoor.fctr.All.X..rcv.glmnet.Y
## .pos 6 2000
## min.outdoor.fctr.All.X..rcv.glmnet.Y
## .pos 1
## max.outdoor.fctr.Final..rcv.glmnet.Y
## .pos 12000
## min.outdoor.fctr.Final..rcv.glmnet.Y
## .pos 2001
## [1] "OOBobs outdoor.fctr.All.X..rcv.glmnet Y: max > max of Train range: 3"
## business_id outdoor.fctr.All.X..rcv.glmnet .pos
## 1998 997 Y 1998
## 2000 999 Y 2000
## 1997 993 Y 1997
## id cor.y exclude.as.feat cor.y.abs cor.high.X freqRatio
## .pos .pos 0.0274973 FALSE 0.0274973 NA 1
## percentUnique zeroVar nzv is.cor.y.abs.low interaction.feat
## .pos 100 FALSE FALSE FALSE NA
## shapiro.test.p.value rsp_var_raw id_var rsp_var max min
## .pos 2.145811e-24 FALSE NA NA 12000 1
## max.outdoor.fctr.N max.outdoor.fctr.Y min.outdoor.fctr.N
## .pos 1999 1996 3
## min.outdoor.fctr.Y max.outdoor.fctr.All.X..rcv.glmnet.Y
## .pos 6 2000
## min.outdoor.fctr.All.X..rcv.glmnet.Y
## .pos 1
## max.outdoor.fctr.Final..rcv.glmnet.Y
## .pos 12000
## min.outdoor.fctr.Final..rcv.glmnet.Y
## .pos 2001
## [1] "OOBobs total range outliers: 5"
## [1] "newobs outdoor.fctr.Final..rcv.glmnet Y: max > max of Train range: 10000"
## business_id outdoor.fctr.Final..rcv.glmnet .pos
## 2001 003sg Y 2001
## 2002 00er5 Y 2002
## 2003 00kad Y 2003
## 2004 00mc6 Y 2004
## 2005 00q7x Y 2005
## 2006 00v0t Y 2006
## business_id outdoor.fctr.Final..rcv.glmnet .pos
## 2384 1b0u4 Y 2384
## 4211 7vfbv Y 4211
## 4996 anids Y 4996
## 7943 lbxpi Y 7943
## 8237 mai4q Y 8237
## 8551 nhrn0 Y 8551
## business_id outdoor.fctr.Final..rcv.glmnet .pos
## 11995 zyrif Y 11995
## 11996 zyvg6 Y 11996
## 11997 zyvjj Y 11997
## 11998 zz8g4 Y 11998
## 11999 zzxkg Y 11999
## 12000 zzxwm Y 12000
## id cor.y exclude.as.feat cor.y.abs cor.high.X freqRatio
## .pos .pos 0.0274973 FALSE 0.0274973 NA 1
## percentUnique zeroVar nzv is.cor.y.abs.low interaction.feat
## .pos 100 FALSE FALSE FALSE NA
## shapiro.test.p.value rsp_var_raw id_var rsp_var max min
## .pos 2.145811e-24 FALSE NA NA 12000 1
## max.outdoor.fctr.N max.outdoor.fctr.Y min.outdoor.fctr.N
## .pos 2000 1997 2
## min.outdoor.fctr.Y max.outdoor.fctr.All.X..rcv.glmnet.Y
## .pos 1 2000
## min.outdoor.fctr.All.X..rcv.glmnet.Y
## .pos 1
## max.outdoor.fctr.Final..rcv.glmnet.Y
## .pos 12000
## min.outdoor.fctr.Final..rcv.glmnet.Y
## .pos 2001
## [1] "newobs total range outliers: 10000"
## [1] TRUE
## [1] "ObsNew output class tables:"
## lunch.-1 dinner.-1 reserve.2 outdoor.3 expensive.-1
## 10000 10000 10000 10000 10000
## liquor.5 table.6 classy.-1 kids.8
## 10000 10000 10000 10000
## [1] 0.4
## [1] "glb_sel_mdl_id: All.X##rcv#glmnet"
## [1] "glb_fin_mdl_id: Final##rcv#glmnet"
## [1] "Cross Validation issues:"
## MFO###myMFO_classfr Random###myrandom_classfr
## 0 0
## Max.cor.Y.rcv.1X1###glmnet
## 0
## max.Accuracy.OOB max.AUCROCR.OOB
## Low.cor.X##rcv#glmnet 0.5015015 0.5084530
## All.X##rcv#glmnet 0.5015015 0.5084530
## Max.cor.Y.rcv.1X1###glmnet 0.5015015 0.5082125
## All.X##rcv#glm 0.5015015 0.5071664
## MFO###myMFO_classfr 0.5015015 0.5000000
## Random###myrandom_classfr 0.5015015 0.4974749
## Max.cor.Y##rcv#rpart 0.5015015 0.4868235
## Final##rcv#glmnet NA NA
## max.AUCpROC.OOB max.Accuracy.fit
## Low.cor.X##rcv#glmnet 0.5164731 0.5008332
## All.X##rcv#glmnet 0.5164731 0.5008332
## Max.cor.Y.rcv.1X1###glmnet 0.5174771 0.5014985
## All.X##rcv#glm 0.5144951 0.5058242
## MFO###myMFO_classfr 0.5000000 0.5014985
## Random###myrandom_classfr 0.5054710 0.5014985
## Max.cor.Y##rcv#rpart 0.5005952 0.5098352
## Final##rcv#glmnet NA 0.4983234
## opt.prob.threshold.fit opt.prob.threshold.OOB
## Low.cor.X##rcv#glmnet 0.4 0.4
## All.X##rcv#glmnet 0.4 0.4
## Max.cor.Y.rcv.1X1###glmnet 0.4 0.4
## All.X##rcv#glm 0.4 0.4
## MFO###myMFO_classfr 0.4 0.4
## Random###myrandom_classfr 0.4 0.4
## Max.cor.Y##rcv#rpart 0.3 0.0
## Final##rcv#glmnet 0.4 NA
## [1] "All.X##rcv#glmnet OOB confusion matrix & accuracy: "
## Prediction
## Reference N Y
## N 0 498
## Y 0 501
## err.abs.fit.sum err.abs.OOB.sum err.abs.trn.sum err.abs.new.sum
## .dummy 500.017 499.4153 999.3585 NA
## .freqRatio.Fit .freqRatio.OOB .freqRatio.Tst .n.Fit .n.New.Y .n.OOB
## .dummy 1 1 1 1001 10000 999
## .n.Trn.N .n.Trn.Y .n.Tst .n.fit .n.new .n.trn err.abs.OOB.mean
## .dummy 997 1003 10000 1001 10000 2000 0.4999153
## err.abs.fit.mean err.abs.new.mean err.abs.trn.mean
## .dummy 0.4995175 NA 0.4996793
## err.abs.fit.sum err.abs.OOB.sum err.abs.trn.sum err.abs.new.sum
## 5.000170e+02 4.994153e+02 9.993585e+02 NA
## .freqRatio.Fit .freqRatio.OOB .freqRatio.Tst .n.Fit
## 1.000000e+00 1.000000e+00 1.000000e+00 1.001000e+03
## .n.New.Y .n.OOB .n.Trn.N .n.Trn.Y
## 1.000000e+04 9.990000e+02 9.970000e+02 1.003000e+03
## .n.Tst .n.fit .n.new .n.trn
## 1.000000e+04 1.001000e+03 1.000000e+04 2.000000e+03
## err.abs.OOB.mean err.abs.fit.mean err.abs.new.mean err.abs.trn.mean
## 4.999153e-01 4.995175e-01 NA 4.996793e-01
## [1] "Features Importance for selected models:"
## All.X..rcv.glmnet.imp Final..rcv.glmnet.imp
## .rnorm 100 100
## [1] "glbObsNew prediction stats:"
##
## N Y
## 0 10000
## label step_major step_minor label_minor bgn end
## 22 predict.data.new 10 0 0 107.229 116.596
## 23 display.session.info 11 0 0 116.596 NA
## elapsed
## 22 9.367
## 23 NA
Null Hypothesis (\(\sf{H_{0}}\)): mpg is not impacted by am_fctr.
The variance by am_fctr appears to be independent. #{r q1, cache=FALSE} # print(t.test(subset(cars_df, am_fctr == "automatic")$mpg, # subset(cars_df, am_fctr == "manual")$mpg, # var.equal=FALSE)$conf) # We reject the null hypothesis i.e. we have evidence to conclude that am_fctr impacts mpg (95% confidence). Manual transmission is better for miles per gallon versus automatic transmission.
## label step_major step_minor label_minor bgn
## 16 fit.models 8 0 0 45.382
## 1 import.data 1 0 0 14.874
## 17 fit.models 8 1 1 68.231
## 22 predict.data.new 10 0 0 107.229
## 18 fit.models 8 2 2 84.050
## 20 fit.data.training 9 0 0 95.986
## 21 fit.data.training 9 1 1 102.606
## 2 inspect.data 2 0 0 35.276
## 19 fit.models 8 3 3 92.749
## 15 select.features 7 0 0 43.729
## 3 scrub.data 2 1 1 39.491
## 11 extract.features.end 3 6 6 41.425
## 14 partition.data.training 6 0 0 42.802
## 12 manage.missing.data 4 0 0 42.402
## 4 transform.data 2 2 2 40.970
## 7 extract.features.image 3 2 2 41.204
## 13 cluster.data 5 0 0 42.743
## 10 extract.features.string 3 5 5 41.368
## 9 extract.features.text 3 4 4 41.311
## 8 extract.features.price 3 3 3 41.266
## 6 extract.features.datetime 3 1 1 41.166
## 5 extract.features 3 0 0 41.144
## end elapsed duration
## 16 68.230 22.848 22.848
## 1 35.275 20.402 20.401
## 17 84.049 15.818 15.818
## 22 116.596 9.367 9.367
## 18 92.748 8.698 8.698
## 20 102.605 6.619 6.619
## 21 107.228 4.622 4.622
## 2 39.491 4.215 4.215
## 19 95.986 3.237 3.237
## 15 45.381 1.653 1.652
## 3 40.969 1.479 1.478
## 11 42.401 0.976 0.976
## 14 43.728 0.926 0.926
## 12 42.742 0.341 0.340
## 4 41.144 0.174 0.174
## 7 41.266 0.062 0.062
## 13 42.802 0.059 0.059
## 10 41.425 0.057 0.057
## 9 41.367 0.056 0.056
## 8 41.310 0.044 0.044
## 6 41.204 0.038 0.038
## 5 41.165 0.021 0.021
## [1] "Total Elapsed Time: 116.596 secs"
## label step_major step_minor label_minor
## 4 fit.models_0_Max.cor.Y.rcv.*X* 1 3 glmnet
## 5 fit.models_0_Low.cor.X 1 4 glmnet
## 2 fit.models_0_MFO 1 1 myMFO_classfr
## 3 fit.models_0_Random 1 2 myrandom_classfr
## 1 fit.models_0_bgn 1 0 setup
## bgn end elapsed duration
## 4 52.215 62.291 10.076 10.076
## 5 62.291 68.216 5.925 5.925
## 2 45.917 49.254 3.337 3.337
## 3 49.255 52.214 2.959 2.959
## 1 45.883 45.916 0.034 0.033
## [1] "Total Elapsed Time: 68.216 secs"